| CONTENTS |
There's a big world out there; we hope that lots of its inhabitants will be interested in your application or applet. The Internet, after all, effortlessly spans the barriers between countries. On the other hand, when you write your applet in U.S. English, using the ASCII character set, you are putting up a barrier. For example, even within countries that can function using the ASCII character set, things as basic as dates and numbers are displayed differently. To a German speaker, the date 3/4/95 means something different than it does to an English speaker. Or, an applet like our calculator from Chapter 10 of Volume 1 could confuse people who do not use the "." to separate the integer and fractional parts of a number.
Now, it is true that many Internet users are able to read English, but they will certainly be more comfortable with applets or applications that are written in their own language and that present data in the format with which they are most familiar. Imagine, for example, that you could write a retirement calculator applet that would change how it displays its results depending on the location of the machine that is downloading it. This kind of applet is immediately more valuable—and smart companies will recognize its value.
The Java programming language was the first language designed from the ground up to support internationalization. From the beginning, it had the one essential feature needed for effective internationalization: it used Unicode for all strings. Unicode support makes it easy to write programs in the Java programming language that manipulate strings in any one of multiple languages.
NOTE
![]() |
The best source for Unicode character tables is The Unicode Standard, Version 3.0, [Addison-Wesley, 2000]. You can also see many of the code charts at http://www.unicode.org. |
Many programmers believe that all they need to do to internationalize their application is to support Unicode and to translate the messages in the user interface. However, as you will see in this chapter, there is a lot more to internationalizing programs than just Unicode support. Operating systems and even browsers may not necessarily be Unicode-ready. For example, it is almost always necessary to have a translation layer between the character sets and fonts of the host machine and the Unicode-centric Java virtual machine. Also, dates, times, currencies—even numbers—are formatted differently in different parts of the world. You need an easy way to configure menu and button names, message strings, and keyboard shortcuts for different languages. You need to trigger the changes in a way that is based on information the ambient machine can report to your program.
In this chapter, you'll see how to write internationalized Java applications and applets. You will see how to localize date and time, numbers and text, and graphical user interfaces, and you'll look at the tools that the SDK offers for writing internationalized programs. (And, by the way, you will see how to write a retirement calculator applet that can change how it displays its results depending on the location of the machine that is downloading it.)
When you look at an application that is adapted to an international market, the most obvious difference you notice is the language. This observation is actually a bit too limiting for true internationalization: Countries can share a common language, but you still may need to do some work to make computer users of both countries happy.[1]
In all cases, menus, button labels, and program messages will need to be translated to the local language; they may also need to be rendered in a different script. There are many more subtle differences; for example, numbers are formatted quite differently in English and in German. The number
123,456.78
should be displayed as
123.456,78
for a German user. That is, the role of the decimal point and the decimal comma separator are reversed! There are similar variations in the display of dates. In the United States, dates are somewhat irrationally displayed as month/day/year. Germany uses the more sensible order of day/month/year, whereas in China, the usage is year/month/day. Thus, the date
3/22/61
should be presented as
22.03.1961
to a German user. Of course, if the month names are written out explicitly, then the difference in languages becomes apparent. The English
March 22, 1961
should be presented as
22. März 1961
in German, or
![]()
in Chinese.
You saw in Volume 1 that the java.text class has methods that can format numbers, currencies, and dates. These methods can, in fact, do much more when you give them a parameter that describes the location. To invoke these methods in a non-country-specific way, you only have to supply objects of the Locale class. A locale describes
A language;
A location;
Optionally, a variant.
For example, in the United States, you use a locale with
language=English, location=United States.
In Germany, you use a locale with
language=German, location=Germany.
Switzerland has four official languages (German, French, Italian, and Rhaeto-Romance). A German speaker in Switzerland would want to use a locale with
language=German, location=Switzerland
This locale would make formatting work similarly to how it would work for the German locale; however, currency values would be expressed in Swiss francs, not German marks.
Variants are, fortunately, rare and are needed only for exceptional or system-dependent situations. For example, the Norwegians are having a hard time agreeing on the spelling of their language (a derivative of Danish). They use two spelling rule sets: a traditional one called Bokmål and a new one called Nynorsk. The traditional spelling would be expressed as a variant
language=Norwegian, location=Norway, variant=Bokmål
There are "Euro" variants for several European locales. For example, the locale
language=German, location=Germany, variant=Euro
uses the euro sign $ instead of DM for displaying currencies.
It is also possible to encode platform-dependent information in the variant.
To express the language and location in a concise and standardized manner, the Java programming language uses codes that were defined by the International Standards Organization. The local language is expressed as a lowercase two-letter code, following ISO-639, and the country code is expressed as an uppercase two-letter code, following ISO-3166. Tables 10-1 and 10-2 show some of the most common codes.
NOTE
![]() |
For a full list of ISO-639 codes, see, for example, http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt. You can find a full list of the ISO-3166 codes at a number of sites, including |
| Language | Code |
|---|---|
| Chinese | zh |
| Danish | da |
| Dutch | nl |
| English | en |
| French | fr |
| Finnish | fi |
| German | de |
| Greek | el |
| Italian | it |
| Japanese | ja |
| Korean | ko |
| Norwegian | no |
| Portuguese | pt |
| Spanish | sp |
| Swedish | sv |
| Turkish | tr |
| Country | Code |
|---|---|
| Austria | AT |
| Belgium | BE |
| Canada | CA |
| China | CN |
| Denmark | DK |
| Finland | FI |
| Germany | DE |
| Great Britain | GB |
| Greece | GR |
| Ireland | IE |
| Italy | IT |
| Japan | JP |
| Korea | KR |
| The Netherlands | NL |
| Norway | NO |
| Portugal | PT |
| Spain | ES |
| Sweden | SE |
| Switzerland | CH |
| Taiwan | TW |
| Turkey | TR |
| United States | US |
These codes do seem a bit random, especially since some of them are derived from local languages (German = Deutsch = de, Chinese = zhongwen = zh), but they are, at least, standardized.
To describe a locale, you concatenate the language, country code, and variant (if any) and pass this string to the constructor of the Locale class. The variant is optional.
Locale germanGermany = new Locale("de", "DE");
Locale germanSwitzerland = new Locale("de", "CH");
Locale norwegianNorwayBokmål = new Locale("no", "NO", "B");
If you want to specify a locale that describes a language only and not a location, use an empty string as the second argument of the constructor.
Locale german = new Locale("de", "");
These kinds of locales can be used only for language-dependent lookups. Since the locales do not specify the location where German is spoken, you cannot use them to determine local currency and date formatting preferences.
For your convenience, the SDK predefines a number of locale objects:
Locale.CANADA Locale.CANADA_FRENCH Locale.CHINA Locale.FRANCE Locale.GERMANY Locale.ITALY Locale.JAPAN Locale.KOREA Locale.PRC Locale.TAIWAN Locale.UK Locale.US
The SDK also predefines a number of language locales that specify just a language without a location.
Locale.CHINESE Locale.ENGLISH Locale.FRENCH Locale.GERMAN Locale.ITALIAN Locale.JAPANESE Locale.KOREAN Locale.SIMPLIFIED_CHINESE Locale.TRADITIONAL_CHINESE
Besides constructing a locale or using a predefined one, you have two other methods for obtaining a locale object.
The static getDefault method of the Locale class gets the default locale as stored by the local operating system. Similarly, in an applet, the getLocale method returns the locale of the user viewing the applet. Finally, all locale-dependent utility classes can return an array of the locales they support. For example,
Locale[] supportedLocales = DateFormat.getAvailableLocales();
returns all locales that the DateFormat class can handle. For example, at the time of this writing, the DateFormat class knows how to format dates in Chinese but not in Vietnamese. Therefore, the getAvailableLocales() returns the Chinese locales but no Vietnamese ones.
NOTE
![]() |
We do not discuss how to create new language-specific elements. If you need to build a Brooklyn- or Texas-centric locale, please consult the SDK documentation. |
Once you have a locale, what can you do with it? Not much, as it turns out. The only useful methods in the Locale class are the ones for identifying the language and country codes. The most important one is getDisplayName. It returns a string describing the locale. This string does not contain the cryptic two-letter codes, but it is in a form that can be presented to a user, such as
German (Switzerland)
Actually, there is a problem here. The display name is issued in the default locale. That may not be appropriate. If your user already selected German as the preferred language, you probably want to present the string in German. You can do just that by giving the German locale as a parameter: The code
Locale loc = new Locale("de", "CH");
System.out.println(loc.getDisplayName(Locale.GERMAN));
prints out
Deutsch (Schweiz)
But the real reason you need a Locale object is to feed it to locale-aware methods. For example, the toLowerCase and toUpperCase methods of the String class can take an argument of type Locale because the rules for forming uppercase letters differ by locale. In France, accents are generally dropped for uppercase letters. But in French-speaking Canada, they are retained. For example, the upper case of "étoile" (star) in France would be "ETOILE," but in Canada it would be "ÉTOILE."
String star = "étoile"; String fr = star.toUpperCase(Locale.FRANCE); // should return "ETOILE" String ca = star.toUpperCase(Locale.CANADA_FRENCH); // returns "ÉTOILE"
Well, not quite: actually, this is the way it is supposed to work, but at least up to SDK 1.4, the toUpperCase method does not pay attention to the French locale. Still, we hope we have given you an idea of what you will be able to do with a Locale object. (Actually, you can give a Locale object to many other methods that carry out locale-specific tasks. You will see many examples in the following sections.)
![]()
static Locale getDefault()
returns the default locale.
static void setDefault(Locale l)
sets the default locale.
String getDisplayName()
returns a name describing the locale, expressed in the current locale.
String getDisplayName(Locale l)
returns a name describing the locale, expressed in the given locale.
String getLanguage()
returns the language code, a lowercase two-letter ISO-639 code.
String getDisplayLanguage()
returns the name of the language, expressed in the current locale.
String getDisplayLanguage(Locale l)
returns the name of the language, expressed in the given locale.
String getCountry()
returns the country code as an uppercase two-letter ISO-3166 code.
String getDisplayCountry()
returns the name of the country, expressed in the current locale.
String getDisplayCountry(Locale l)
returns the name of the country, expressed in the given locale.
String getVariant()
returns the variant string.
String getDisplayVariant()
returns the name of the variant, expressed in the current locale.
String getDisplayVariant(Locale l)
returns the name of the variant, expressed in the given locale.
String toString()
returns a description of the locale, with the language, country, and variant separated by underscores (e.g., "de_CH").
We already mentioned how number and currency formatting is highly locale dependent. The Java programming language supplies a collection of formatter objects that can format and parse numeric values in the java.text class. You go through the following steps to format a number for a particular locale.
Get the locale object, as described in the preceding section.
Use a "factory method" to obtain a formatter object.
Use the formatter object for formatting and parsing.
The factory methods are static methods of the NumberFormat class that take a Locale argument. There are three factory methods: getNumberInstance, getCurrencyInstance, and getPercentInstance. These methods return objects that can format and parse numbers, currency amounts, and percentages, respectively. For example, here is how you can format a currency value in German.
Locale loc = new Locale("de", "DE");
NumberFormat currFmt = NumberFormat.getCurrencyInstance(loc);
double amt = 123456.78;
System.out.println(currFmt.format(amt));
This code prints
123.456,78 DM
Note that the currency symbol is DM and that it is placed at the end of the string. Also, note the reversal of decimal points and decimal commas.
Conversely, if you want to read in a number that was entered or stored with the conventions of a certain locale, then you use the parse method, which automatically uses the default locale. For example, the following code parses the value that the user typed into a text field. The parse method can deal with decimal points and commas, as well as digits in other languages.
TextField inputField; . . . NumberFormat fmt = NumberFormat.getNumberInstance(); // get number formatter for default locale Number input = fmt.parse(inputField.getText().trim()); double x = input.doubleValue();
The return type of parse is the abstract type Number. The returned object is either a Double or a Long wrapper object, depending on whether the parsed number was a floating-point number. If you don't care about the distinction, you can simply use the doubleValue method of the Number class to retrieve the wrapped number.
If the number is not in the correct form, the method throws a ParseException. For example, leading white space in the string is not allowed. (Call trim to remove it.) However, any characters that follow the number in the string are simply ignored, so no exception is thrown.
Note that the classes returned by the getXxxInstance factory methods are not actually of type NumberFormat. The NumberFormat type is an abstract class, and the actual formatters belong to one of its subclasses.
The factory methods merely know how to locate the object that belongs to a particular locale.
It is quite obvious that it takes effort to produce a formatter object for a particular locale. Although the SDK supports only a limited number of localized formatters, more should follow over time, and you can, of course, write your own.
You can get a list of the currently supported locales with the static getAvailableLocales method. That method returns an array of the locales for which number formatter objects can be obtained.
The sample program for this section lets you experiment with number formatters (see Figure 10-1). The combo box at the top of the figure contains all locales with number formatters. You can choose between number, currency, and percentage formatters. Each time you make another choice, the number in the text field is reformatted. If you go through a few locales, then you get a good impression of how many ways there are to format a number or currency value. You can also type a different number and click on the Parse button to call the parse method, which tries to parse what you entered. If your input is successfully parsed, then it is passed to format and the result is displayed. If parsing fails, then a "Parse error" message is displayed in the text field.

The code, shown in Example 10-1, is fairly straightforward. In the constructor, we call NumberFormat.getAvailableLocales. For each locale, we call getDisplayName, and we fill a combo box with the strings that the getDisplayName method returns. Whenever the user selects another locale or clicks on one of the radio buttons, we create a new formatter object and update the text field. When the user clicks on the Parse button, we call the parse method to do the actual parsing, based on the locale selected.
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.text.*;
4. import java.util.*;
5. import javax.swing.*;
6.
7. /**
8. This program demonstrates formatting numbers under
9. various locales.
10. */
11. public class NumberFormatTest
12. {
13. public static void main(String[] args)
14. {
15. JFrame frame = new NumberFormatFrame();
16. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. frame.show();
18. }
19. }
20.
21. /**
22. This frame contains radio buttons to select a number format,
23. a combo box to pick a locale, a text field to display
24. a formatted number, and a button to parse the text field
25. contents.
26. */
27. class NumberFormatFrame extends JFrame
28.{
29. public NumberFormatFrame()
30. {
31. setSize(WIDTH, HEIGHT);
32. setTitle("NumberFormatTest");
33.
34. getContentPane().setLayout(new GridBagLayout());
35.
36. ActionListener listener = new
37. ActionListener()
38. {
39. public void actionPerformed(ActionEvent event)
40. {
41. updateDisplay();
42. }
43. };
44.
45. JPanel p = new JPanel();
46. addRadioButton(p, numberRadioButton, rbGroup, listener);
47. addRadioButton(p, currencyRadioButton, rbGroup, listener);
48. addRadioButton(p, percentRadioButton, rbGroup, listener);
49.
50. GridBagConstraints gbc = new GridBagConstraints();
51. gbc.fill = GridBagConstraints.NONE;
52. gbc.anchor = GridBagConstraints.EAST;
53. add(new JLabel("Locale"), gbc, 0, 0, 1, 1);
54. add(p, gbc, 1, 1, 1, 1);
55. add(parseButton, gbc, 0, 2, 1, 1);
56. gbc.anchor = GridBagConstraints.WEST;
57. add(localeCombo, gbc, 1, 0, 1, 1);
58. gbc.fill = GridBagConstraints.HORIZONTAL;
59. add(numberText, gbc, 1, 2, 1, 1);
60.
61. locales = NumberFormat.getAvailableLocales();
62. for (int i = 0; i < locales.length; i++)
63. localeCombo.addItem(locales[i].getDisplayName());
64. localeCombo.setSelectedItem(
65. Locale.getDefault().getDisplayName());
66. currentNumber = 123456.78;
67. updateDisplay();
68.
69. localeCombo.addActionListener(listener);
70.
71. parseButton.addActionListener(new
72. ActionListener()
73. {
74. public void actionPerformed(ActionEvent event)
75. {
76. String s = numberText.getText();
77. try
78. {
79. Number n = currentNumberFormat.parse(s);
80. if (n != null)
81. {
82. currentNumber = n.doubleValue();
83. updateDisplay();
84. }
85. else
86. {
87. numberText.setText("Parse error: " + s);
88. }
89. }
90. catch(ParseException e)
91. {
92. numberText.setText("Parse error: " + s);
93. }
94. }
95. });
96. }
97.
98. /**
99. A convenience method to add a component to given grid bag
100. layout locations.
101. @param c the component to add
102. @param gbc the grid bag constraints to use
103. @param x the x grid position
104. @param y the y grid position
105. @param w the grid width
106. @param h the grid height
107. */
108. public void add(Component c, GridBagConstraints gbc,
109. int x, int y, int w, int h)
110. {
111. gbc.gridx = x;
112. gbc.gridy = y;
113. gbc.gridwidth = w;
114. gbc.gridheight = h;
115. getContentPane().add(c, gbc);
116. }
117.
118. /**
119. Adds a radio button to a container.
120. @param p the container into which to place the button
121. @param b the button
122. @param g the button group
123. @param listener the button listener
124. */
125. public void addRadioButton(Container p, JRadioButton b,
126. ButtonGroup g, ActionListener listener)
127. {
128. b.setSelected(g.getButtonCount() == 0);
129. b.addActionListener(listener);
130. g.add(b);
131. p.add(b);
132. }
133.
134. /**
135. Updates the display and formats the number according
136. to the user settings.
137. */
138. public void updateDisplay()
139. {
140. Locale currentLocale = locales[
141. localeCombo.getSelectedIndex()];
142. currentNumberFormat = null;
143. if (numberRadioButton.isSelected())
144. currentNumberFormat
145. = NumberFormat.getNumberInstance(currentLocale);
146. else if (currencyRadioButton.isSelected())
147. currentNumberFormat
148. = NumberFormat.getCurrencyInstance(currentLocale);
149. else if (percentRadioButton.isSelected())
150. currentNumberFormat
151. = NumberFormat.getPercentInstance(currentLocale);
152. String n = currentNumberFormat.format(currentNumber);
153. numberText.setText(n);
154. }
155.
156. private Locale[] locales;
157.
158. private double currentNumber;
159.
160. private JComboBox localeCombo = new JComboBox();
161. private JButton parseButton = new JButton("Parse");
162. private JTextField numberText = new JTextField(30);
163. private JRadioButton numberRadioButton
164. = new JRadioButton("Number");
165. private JRadioButton currencyRadioButton
166. = new JRadioButton("Currency");
167. private JRadioButton percentRadioButton
168. = new JRadioButton("Percent");
169. private ButtonGroup rbGroup = new ButtonGroup();
170. private NumberFormat currentNumberFormat;
171. private static final int WIDTH = 400;
172. private static final int HEIGHT = 200;
173. }
![]()
static Locale[] getAvailableLocales()
returns an array of Locale objects for which NumberFormat formatters are available.
static NumberFormat getNumberInstance()
static NumberFormat getNumberInstance(Locale l)
static NumberFormat getCurrencyInstance()
static NumberFormat getCurrencyInstance(Locale l)
static NumberFormat getPercentInstance()
static NumberFormat getPercentInstance(Locale l)
return a formatter for numbers, currency amounts, or percentage values for the current locale or for the given locale.
String format(double x)
String format(long x)
return the string resulting from formatting the given floating-point number or integer.
Number parse(String s)
parses the given string and returns the number value, as a Double if the input string described a floating-point number, and as a Long otherwise. The beginning of the string must contain a number; no leading white space is allowed. The number can be followed by other characters, which are ignored. Throws a ParseException if parsing was not successful.
void setParseIntegerOnly(boolean b)
boolean isParseIntegerOnly()
set or get a flag to indicate whether this formatter should parse only integer values.
void setGroupingUsed(boolean b)
boolean isGroupingUsed()
set or get a flag to indicate whether this formatter emits and recognizes decimal separators (such as 100,000).
void setMinimumIntegerDigits(int n)
int getMinimumIntegerDigits()
void setMaximumIntegerDigits(int n)
int getMaximumIntegerDigits()
void setMinimumFractionDigits(int n)
int getMinimumFractionDigits()
void setMaximumFractionDigits(int n)
int getMaximumFractionDigits()
set or get the maximum or minimum number of digits allowed in the integer or fractional part of a number.
When you are formatting date and time, there are four locale-dependent issues you need to worry about:
The names of months and weekdays should be presented in the local language.
There will be local preferences for the order of year, month, and day.
The Gregorian calendar may not be the local preference for expressing dates.
The time zone of the location must be taken into account.
The Java DateFormat class handles these issues. It is easy to use and quite similar to the NumberFormat class. First, you get a locale. You can use the default locale or call the static getAvailableLocales method to obtain an array of locales that support date formatting. Then, you call one of the three factory methods:
fmt = DateFormat.getDateInstance(dateStyle, loc); fmt = DateFormat.getTimeInstance(timeStyle, loc); fmt = DateFormat.getDateTimeInstance(dateStyle, timeStyle, loc);
To specify the desired style, these factory methods have a parameter that is one of the following constants:
DateFormat.DEFAULT
DateFormat.FULL (e.g., Thursday, September 18, 1997 8:42:46 o'clock A.M.PDT for the U.S. locale)
DateFormat.LONG (e.g., September 18, 1997 8:42:46 A.M. PDT for the U.S. locale)
DateFormat.MEDIUM (e.g., Sep 18, 1997 8:42:46 A.M. for the U.S. locale)
DateFormat.SHORT (e.g., 9/18/97 8:42 A.M. for the U.S. locale)
The factory method returns a formatting object that you can then use to format dates.
Date now = new Date(); String s = fmt.format(now);
Just as with the NumberFormat class, you can use the parse method to parse a date that the user typed. For example, the following code parses the value that the user typed into a text field.
TextField inputField; . . . DateFormat fmt = DateFormat.getDateInstance(DateFormat.MEDIUM); // get date formatter for default locale Date input = fmt.parse(inputField.getText().trim());
If the number was not typed correctly, this code throws a ParseException. Note that leading white space in the string is not allowed here, either. You should again call trim to remove it. However, any characters that follow the number in the string will again be ignored. Unfortunately, the user must type the date exactly in the expected format. For example, if the format is set to MEDIUM in the U.S. locale, then dates are expected to look like
Sep 18, 1997
If the user types
Sep 18 1997
(without the comma) or the short format
9/18/97
then a parse error results.
A lenient flag interprets dates leniently. For example, February 30, 1999 will be automatically converted to March 2, 1999. This seems dangerous, but, unfortunately, it is the default. You should probably turn off this feature. The calendar object that is used to interpret the parsed date will throw an IllegalArgumentException when the user enters an invalid day/month/year combination.
Example 10-2 shows the DateFormat class in action. You can select a locale and see how the date and time are formatted in different places around the world. If you see question-mark characters in the output, then you don't have the fonts installed for displaying characters in the local language. For example, if you pick a Chinese locale, the date may be expressed as
1997?9?19?
Figure 10-2 shows the program running under Chinese Windows; as you can see, it correctly displays the output.

You can also experiment with parsing. Type in a date or time, click the Parse lenient checkbox if desired, and click on the Parse date or Parse time button.
The only mysterious feature about the code is probably the EnumCombo class. We used this class to solve the following technical problem. We wanted to fill a combo with values such as Short, Medium, and Long and then automatically convert the user's selection to integer values DateFormat.SHORT, DateFormat.MEDIUM, and DateFormat.LONG. To do this, we convert the user's choice to upper case, replace all spaces with underscores, and then use reflection to find the value of the static field with that name. (See Chapter 5 of Volume 1 for more details about reflection.)
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.text.*;
4. import java.util.*;
5. import javax.swing.*;
6.
7. /**
8. This program demonstrates formatting dates under
9. various locales.
10. */
11. public class DateFormatTest
12. {
13. public static void main(String[] args)
14. {
15. JFrame frame = new DateFormatFrame();
16. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. frame.show();
18. }
19. }
20.
21. /**
22. This frame contains combo boxes to pick a locale, date and
23. time formats, text fields to display formatted date and time,
24. buttons to parse the text field contents, and a "lenient"
25. check box.
26. */
27. class DateFormatFrame extends JFrame
28. {
29. public DateFormatFrame()
30. {
31. setSize(WIDTH, HEIGHT);
32. setTitle("DateFormatTest");
33.
34. getContentPane().setLayout(new GridBagLayout());
35. GridBagConstraints gbc = new GridBagConstraints();
36. gbc.fill = GridBagConstraints.NONE;
37. gbc.anchor = GridBagConstraints.EAST;
38. add(new JLabel("Locale"), gbc, 0, 0, 1, 1);
39. add(new JLabel("Date style"), gbc, 0, 1, 1, 1);
40. add(new JLabel("Time style"), gbc, 2, 1, 1, 1);
41. add(new JLabel("Date"), gbc, 0, 2, 1, 1);
42. add(new JLabel("Time"), gbc, 0, 3, 1, 1);
43. gbc.anchor = GridBagConstraints.WEST;
44. add(localeCombo, gbc, 1, 0, 2, 1);
45. add(dateStyleCombo, gbc, 1, 1, 1, 1);
46. add(timeStyleCombo, gbc, 3, 1, 1, 1);
47. add(dateParseButton, gbc, 3, 2, 1, 1);
48. add(timeParseButton, gbc, 3, 3, 1, 1);
49. add(lenientCheckbox, gbc, 0, 4, 2, 1);
50. gbc.fill = GridBagConstraints.HORIZONTAL;
51. add(dateText, gbc, 1, 2, 2, 1);
52. add(timeText, gbc, 1, 3, 2, 1);
53.
54. locales = DateFormat.getAvailableLocales();
55. for (int i = 0; i < locales.length; i++)
56. localeCombo.addItem(locales[i].getDisplayName());
57. localeCombo.setSelectedItem(
58. Locale.getDefault().getDisplayName());
59. currentDate = new Date();
60. currentTime = new Date();
61. updateDisplay();
62.
63. ActionListener listener = new
64. ActionListener()
65. {
66. public void actionPerformed(ActionEvent event)
67. {
68. updateDisplay();
69. }
70. };
71.
72. localeCombo.addActionListener(listener);
73. dateStyleCombo.addActionListener(listener);
74. timeStyleCombo.addActionListener(listener);
75.
76. dateParseButton.addActionListener(new
77. ActionListener()
78. {
79. public void actionPerformed(ActionEvent event)
80. {
81. String d = dateText.getText();
82. try
83. {
84. currentDateFormat.setLenient
85. (lenientCheckbox.isSelected());
86. Date date = currentDateFormat.parse(d);
87. currentDate = date;
88. updateDisplay();
89. }
90. catch(ParseException e)
91. {
92. dateText.setText("Parse error: " + d);
93. }
94. catch(IllegalArgumentException e)
95. {
96. dateText.setText("Argument error: " + d);
97. }
98. }
99. });
100.
101. timeParseButton.addActionListener(new
102. ActionListener()
103. {
104. public void actionPerformed(ActionEvent event)
105. {
106. String t = timeText.getText();
107. try
108. {
109. currentDateFormat.setLenient
110. (lenientCheckbox.isSelected());
111. Date date = currentTimeFormat.parse(t);
112. currentTime = date;
113. updateDisplay();
114. }
115. catch(ParseException e)
116. {
117. timeText.setText("Parse error: " + t);
118. }
119. catch(IllegalArgumentException e)
120. {
121. timeText.setText("Argument error: " + t);
122. }
123. }
124. });
125. }
126.
127. /**
128. A convenience method to add a component to given grid bag
129. layout locations.
130. @param c the component to add
131. @param gbc the grid bag constraints to use
132. @param x the x grid position
133. @param y the y grid position
134. @param w the grid width
135. @param h the grid height
136. */
137. public void add(Component c, GridBagConstraints gbc,
138. int x, int y, int w, int h)
139. {
140. gbc.gridx = x;
141. gbc.gridy = y;
142. gbc.gridwidth = w;
143. gbc.gridheight = h;
144. getContentPane().add(c, gbc);
145. }
146.
147. /**
148. Updates the display and formats the date according
149. to the user settings.
150. */
151. public void updateDisplay()
152. {
153. Locale currentLocale = locales[
154. localeCombo.getSelectedIndex()];
155. int dateStyle = dateStyleCombo.getValue();
156. currentDateFormat
157. = DateFormat.getDateInstance(dateStyle,
158. currentLocale);
159. String d = currentDateFormat.format(currentDate);
160. dateText.setText(d);
161. int timeStyle = timeStyleCombo.getValue();
162. currentTimeFormat
163. = DateFormat.getTimeInstance(timeStyle,
164. currentLocale);
165. String t = currentTimeFormat.format(currentTime);
166. timeText.setText(t);
167. }
168.
169. private Locale[] locales;
170.
171. private Date currentDate;
172. private Date currentTime;
173. private DateFormat currentDateFormat;
174. private DateFormat currentTimeFormat;
175.
176. private JComboBox localeCombo = new JComboBox();
177. private EnumCombo dateStyleCombo
178. = new EnumCombo(DateFormat.class,
179. new String[] { "Default", "Full", "Long",
180. "Medium", "Short" });
181. private EnumCombo timeStyleCombo
182. = new EnumCombo(DateFormat.class,
183. new String[] { "Default", "Full", "Long",
184. "Medium", "Short" });
185. private JButton dateParseButton = new JButton("Parse date");
186. private JButton timeParseButton = new JButton("Parse time");
187. private JTextField dateText = new JTextField(30);
188. private JTextField timeText = new JTextField(30);
189. private JTextField parseText = new JTextField(30);
190. private JCheckBox lenientCheckbox
191. = new JCheckBox("Parse lenient", true);
192. private static final int WIDTH = 400;
193. private static final int HEIGHT = 200;
194. }
195.
196. /**
197. A combo box that lets users choose from among static field
198. values whose names are given in the constructor.
199.*/
200.class EnumCombo extends JComboBox
201.{
202. /**
203. Constructs an EnumCombo.
204. @param cl a class
205. @param labels an array of static field names of cl
206. */
207. public EnumCombo(Class cl, String[] labels)
208. {
209. for (int i = 0; i < labels.length; i++)
210. {
211. String label = labels[i];
212. String name = label.toUpperCase().replace(' ', '_');
213. int value = 0;
214. try
215. {
216. java.lang.reflect.Field f = cl.getField(name);
217. value = f.getInt(cl);
218. }
219. catch(Exception e)
220. {
221. label = "(" + label + ")";
222. }
223. table.put(label, new Integer(value));
224. addItem(label);
225. }
226. setSelectedItem(labels[0]);
227. }
228.
229. /**
230. Returns the value of the field that the user selected.
231. @return the static field value
232. */
233. public int getValue()
234. {
235. return ((Integer)table.get(getSelectedItem())).intValue();
236. }
237.
238. private Map table = new HashMap();
239.}
![]()
static Locale[] getAvailableLocales()
returns an array of Locale objects for which DateFormat formatters are available.
static DateFormat getDateInstance(int dateStyle)
static DateFormat getDateInstance(int dateStyle, Locale l)
static DateFormat getTimeInstance(int timeStyle)
static DateFormat getTimeInstance(int timeStyle, Locale l)
static DateFormat getDateTimeInstance(int dateStyle, int timeStyle)
static DateFormat getDateTimeInstance(int dateStyle, int timeStyle, Locale l)
return a formatter for date, time, or date and time for the default locale or the given locale.
| Parameters: | dateStyle, timeStyle | one of DEFAULT, FULL, LONG, MEDIUM, SHORT |
String format(Date d)
returns the string resulting from formatting the given date/time.
Date parse(String s)
parses the given string and returns the date/time described in it. The beginning of the string must contain a date or time; no leading white space is allowed. The date can be followed by other characters, which are ignored. Throws a ParseException if parsing was not successful.
void setLenient(boolean b)
boolean isLenient()
set or get a flag to indicate whether parsing should be lenient or strict. In lenient mode, dates such as February 30, 1999 will be automatically converted to March 2, 1999. The default is lenient mode.
void setCalendar(Calendar cal)
Calendar getCalendar()
set or get the calendar object used for extracting year, month, day, hour, minute, and second from the Date object. Use this method if you do not want to use the default calendar for the locale (usually the Gregorian calendar).
void setTimeZone(TimeZone tz)
TimeZone getTimeZone()
set or get the time zone object used for formatting the time. Use this method if you do not want to use the default time zone for the locale. The default time zone is the time zone of the default locale, as obtained from the operating system. For the other locales, it is the preferred time zone in the geographical location.
void setNumberFormat(NumberFormat f)
NumberFormat getNumberFormat()
set or get the number format used for formatting the numbers used for representing year, month, day, hour, minute, and second.
There are many localization issues to deal with when you display even the simplest text in an internationalized application. In this section, we work on the presentation and manipulation of text strings. For example, the sorting order for strings is clearly locale specific. Obviously, you also need to localize the text itself: directions, labels, and messages will all need to be translated. (Later in this chapter, you'll see how to build resource bundles. These let you collect a set of message strings that work for a particular language.)
Sorting strings in alphabetical order is easy when the strings are made up of only English ASCII characters. You just compare the strings with the compareTo method of the String class. The value of
a.compareTo(b)
is a negative number if a is lexicographically less than b, 0 if they are identical, and positive otherwise.
Unfortunately, unless all your words are in uppercase English ASCII characters, this method is useless. The problem is that the compareTo method in the Java programming language uses the values of the Unicode character to determine the ordering. For example, lowercase characters have a higher Unicode value than do uppercase characters, and accented characters have even higher values. This leads to absurd results; for example, the following five strings are ordered according to the compareTo method:
America Zulu ant zebra Ångstrom
For dictionary ordering, you want to consider upper case and lower case to be equivalent. To an English speaker, the sample list of words would be ordered as
America Ångstrom ant zebra Zulu
However, that order would not be acceptable to a Danish user. In Danish, the letter Å is a different letter than the letter A, and it is collated after the letter Z! That is, a Danish user would want the words to be sorted as
America ant zebra Zulu Ångstrom
Fortunately, once you are aware of the problem, collation is quite easy. As always, you start by obtaining a Locale object. Then, you call the getInstance factory method to obtain a Collator object. Finally, you use the compare method of the collator, not the compareTo method of the String class, whenever you want to sort strings.
Locale loc = . . .; Collator coll = Collator.getInstance(loc); if (coll.compare(a, b) < 0) // a comes before b . . .;
Most importantly, the Collator class implements the Comparator interface. Therefore, you can pass a collator object to the Collections.sort method to sort a list of strings:
Collections.sort(strings, coll);
You can set a collator's strength to select how selective it should be. Character differences are classified as primary, secondary, and tertiary. For example, in English, the difference between "A" and "Z" is considered primary, the difference between "A" and "Å" is secondary, and between "A" and "a" is tertiary.
By setting the collator's strength to Collator.PRIMARY, you tell it to pay attention only to primary differences. By setting the strength to Collator.SECONDARY, the collator will take secondary differences into account. That is, two strings will be more likely to be considered different when the strength is set to "secondary." For example,
// assuming English locale
String a = "Angstrom";
String b = "Ångstrom";
coll.setStrength(Collator.PRIMARY);
if (coll.compare(a, b) == 0) System.out.print("same");
else System.out.print("different");
// will print "same"
coll.setStrength(Collator.SECONDARY);
if (coll.compare(a, b) == 0) System.out.print("same");
else System.out.print("different");
// will print "different"
Table 10-3 shows how a sample set of strings is sorted with the three collation strengths. Note that the strength indicates only whether two strings are considered identical.
| Input | PRIMARY | SECONDARY | TERTIARY |
|---|---|---|---|
| Ant, | Angstrom = Ångstrom, | Angstrom, | Angstrom, |
| ant, | Ant = ant, | Ångstrom, | Ångstrom, |
| Angstrom, | Ant = ant | Ant, | |
| Ångstrom, | ant |
Finally, there is one technical setting, the decomposition mode. The default, "canonical decomposition," is appropriate for most uses. If you choose "no decomposition," then accented characters are not decomposed into their base form + accent. This option is faster, but it gives correct results only when the input does not contain accented characters. (It never makes sense to sort accented characters by their Unicode values.) Finally, "full decomposition" analyzes Unicode variants, that is, Unicode characters that ought to be considered identical. For example, Japanese displays have two ways of showing English characters, called half-width and full-width. The half-width characters have normal character spacing, whereas the full-width characters are spaced in the same grid as the ideographs. (One could argue that this is a presentation issue and it should not have resulted in different Unicode characters, but we don't make the rules.) With full decomposition, half-width and full-width variants of the same letter are recognized as identical.
It is wasteful to have the collator decompose a string many times. If one string is compared many times against other strings, then you can save the decomposition in a collation key object. The getCollationKey method returns a CollationKey object that you can use for further, faster comparisons. Here is an example:
String a = . . .; CollationKey aKey = coll.getCollationKey(a); if (aKey.compareTo(coll.getCollationKey(b) == 0) // fast comparison . . .
The program in Example 10-3 lets you experiment with collation order. Type a word into the text field and click on Add to add it to the list of words. Each time you add another word, or change the locale, strength, or decomposition mode, the list of words is sorted again. An = sign indicates words that are considered identical (see Figure 10-3).

1. import java.io.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. import java.text.*;
5. import java.util.*;
6. import java.util.List;
7. import javax.swing.*;
8.
9. /**
10. This program demonstrates collating strings under
11. various locales.
12. */
13. public class CollationTest
14. {
15. public static void main(String[] args)
16. {
17. JFrame frame = new CollationFrame();
18. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19. frame.show();
20. }
21. }
22.
23. /**
24. This frame contains combo boxes to pick a locale, collation
25. strength and decomposition rules, a text field and button
26. to add new strings, and a text area to list the collated
27. strings.
28. */
29. class CollationFrame extends JFrame
30. {
31. public CollationFrame()
32. {
33. setSize(WIDTH, HEIGHT);
34. setTitle("CollationTest");
35.
36. getContentPane().setLayout(new GridBagLayout());
37. GridBagConstraints gbc = new GridBagConstraints();
38. gbc.fill = GridBagConstraints.NONE;
39. gbc.anchor = GridBagConstraints.EAST;
40. add(new JLabel("Locale"), gbc, 0, 0, 1, 1);
41. add(new JLabel("Strength"), gbc, 0, 1, 1, 1);
42. add(new JLabel("Decomposition"), gbc, 0, 2, 1, 1);
43. add(addButton, gbc, 0, 3, 1, 1);
44. gbc.anchor = GridBagConstraints.WEST;
45. add(localeCombo, gbc, 1, 0, 1, 1);
46. add(strengthCombo, gbc, 1, 1, 1, 1);
47. add(decompositionCombo, gbc, 1, 2, 1, 1);
48. gbc.fill = GridBagConstraints.HORIZONTAL;
49. add(newWord, gbc, 1, 3, 1, 1);
50. gbc.fill = GridBagConstraints.BOTH;
51. add(new JScrollPane(sortedWords), gbc, 1, 4, 1, 1);
52.
53. locales = Collator.getAvailableLocales();
54. for (int i = 0; i < locales.length; i++)
55. localeCombo.addItem(locales[i].getDisplayName());
56. localeCombo.setSelectedItem(
57. Locale.getDefault().getDisplayName());
58.
59. strings.add("America");
60. strings.add("ant");
61. strings.add("Zulu");
62. strings.add("zebra");
63. strings.add("
ngstrom");
64. strings.add("Angstrom");
65. strings.add("Ant");
66. updateDisplay();
67.
68. addButton.addActionListener(new
69. ActionListener()
70. {
71. public void actionPerformed(ActionEvent event)
72. {
73. strings.add(newWord.getText());
74. updateDisplay();
75. }
76. });
77.
78. ActionListener listener = new
79. ActionListener()
80. {
81. public void actionPerformed(ActionEvent event)
82. {
83. updateDisplay();
84. }
85. };
86.
87. localeCombo.addActionListener(listener);
88. strengthCombo.addActionListener(listener);
89. decompositionCombo.addActionListener(listener);
90. }
91.
92. /**
93. A convenience method to add a component to given grid bag
94. layout locations.
95. @param c the component to add
96. @param gbc the grid bag constraints to use
97. @param x the x grid position
98. @param y the y grid position
99. @param w the grid width
100. @param h the grid height
101. */
102. public void add(Component c, GridBagConstraints gbc,
103. int x, int y, int w, int h)
104. {
105. gbc.gridx = x;
106. gbc.gridy = y;
107. gbc.gridwidth = w;
108. gbc.gridheight = h;
109. getContentPane().add(c, gbc);
110. }
111.
112. /**
113. Updates the display and collates the strings according
114. to the user settings.
115. */
116. public void updateDisplay()
117. {
118. Locale currentLocale = locales[
119. localeCombo.getSelectedIndex()];
120.
121. currentCollator
122. = Collator.getInstance(currentLocale);
123. currentCollator.setStrength(strengthCombo.getValue());
124. currentCollator.setDecomposition(
125. decompositionCombo.getValue());
126.
127. Collections.sort(strings, currentCollator);
128.
129. sortedWords.setText("");
130. for (int i = 0; i < strings.size(); i++)
131. {
132. String s = (String)strings.get(i);
133. if (i > 0
134. && currentCollator.compare(s, strings.get(i - 1)) == 0)
135. {
136. sortedWords.append("= ");
137. }
138. sortedWords.append(s + "\n");
139. }
140. }
141.
142. private Locale[] locales;
143. private List strings = new ArrayList();
144. private Collator currentCollator;
145.
146. private JComboBox localeCombo = new JComboBox();
147. private EnumCombo strengthCombo
148. = new EnumCombo(Collator.class,
149. new String[] { "Primary", "Secondary", "Tertiary" });
150. private EnumCombo decompositionCombo
151. = new EnumCombo(Collator.class,
152. new String[] { "Canonical Decomposition",
153. "Full Decomposition", "No Decomposition" });
154. private JTextField newWord = new JTextField(20);
155. private JTextArea sortedWords = new JTextArea(10, 20);
156. private JButton addButton = new JButton("Add");
157. private static final int WIDTH = 400;
158. private static final int HEIGHT = 400;
159.}
160.
161. /**
162. A combo box that lets users choose from among static field
163. values whose names are given in the constructor.
164. */
165. class EnumCombo extends JComboBox
166. {
167. /**
168. Constructs an EnumCombo.
169. @param cl a class
170. @param labels an array of static field names of cl
171. */
172. public EnumCombo(Class cl, String[] labels)
173. {
174. for (int i = 0; i < labels.length; i++)
175. {
176. String label = labels[i];
177. String name = label.toUpperCase().replace(' ', '_');
178. int value = 0;
179. try
180. {
181. java.lang.reflect.Field f = cl.getField(name);
182. value = f.getInt(cl);
183. }
184. catch(Exception e)
185. {
186. label = "(" + label + ")";
187. }
188. table.put(label, new Integer(value));
189. addItem(label);
190. }
191. setSelectedItem(labels[0]);
192. }
193.
194. /**
195. Returns the value of the field that the user selected.
196. @return the static field value
197. */
198. public int getValue()
199. {
200. return ((Integer)table.get(getSelectedItem())).intValue();
201. }
202.
203. private Map table = new HashMap();
204.}
![]()
static Locale[] getAvailableLocales()
returns an array of Locale objects for which Collator objects are available.
static Collator getInstance()
static Collator getInstance(Locale l)
return a collator for the default locale or the given locale.
int compare(String a, String b)
returns a negative value if a comes before b, 0 if they are considered identical, a positive value otherwise.
boolean equals(String a, String b)
returns true if they are considered identical, false otherwise.
void setStrength(int strength) / int getStrength()
sets or gets the strength of the collator. Stronger collators tell more words apart. Strength values are Collator.PRIMARY, Collator.SECONDARY, and Collator.TERTIARY.
void setDecomposition(int decomp) / int getDecompositon()
sets or gets the decomposition mode of the collator. The more a collator decomposes a string, the more strict it will be in deciding whether two strings ought to be considered identical. Decomposition values are Collator.NO_DECOMPOSITION, Collator.CANONICAL_DECOMPOSITION, and Collator.FULL_DECOMPOSITION.
CollationKey getCollationKey(String a)
returns a collation key that contains a decomposition of the characters in a form that can be quickly compared against another collation key.
![]()
int compareTo(CollationKey b)
returns a negative value if this key comes before b, 0 if they are considered identical, a positive value otherwise.
Consider a "sentence" in an arbitrary language: Where are its "words"? Answering this question sounds trivial, but once you deal with multiple languages, then just as with collation, it isn't as simple as you might think. Actually, the situation is even worse than you might think—consider the problem of determining where a character starts and ends. If you have a string such as "Hello", then it is trivial to break it up into five individual characters: H|e|l|l|o. But accents throw a monkey wrench into this simple model. There are two ways of describing an accented character such as ä, namely, the character ä itself (Unicode \u00E4), or the character a followed by a combining diaeresis .. (Unicode \u0308). That is, the string with four Unicode characters Ba..r is a sequence of three logical characters:
B|a..|r. This situation is still relatively easy; it gets much more complex for Asian languages such as the Korean Hangul script.
What about word breaks? Word breaks, of course, are at the beginning and the end of a word. In English, this is simple: sequences of characters are words. For example, the word breaks in
The quick, brown fox jump-ed over the lazy dog.
are
The| |quick|,| |brown| |fox| |jump-ed| |over| |the| |lazy| |dog.|
(The hyphen in jump-ed indicates a soft hyphen.)
Line boundaries are positions where a line can be broken on the screen or in printed text. In English text, this decision is relatively easy. Lines can be broken before a word or after a hyphen. For example, the line breaks in our sample sentence are
The |quick, |brown |fox |jump-|ed |over |the |lazy |dog.|
Note that line breaks are the points where a line can be broken, not the points where the lines are actually broken.
Determining character, word, and line boundaries is simple for European and Asian ideographic scripts, but it is quite complex for others, such as Devanagari, the script used to write classical Sanskrit and modern Hindi.
Finally, you will want to know about breaks between sentences. In English, for example, sentence breaks occur after periods, exclamation marks, and question marks.
Use the BreakIterator class to find out where you can break up text into components such as characters, words, lines, and sentences. You would use these classes when writing code for editing, displaying, and printing text.
Luckily, the break iterator class does not blindly break sentences at every period. It knows about the rules for periods inside quotation marks, and about "…" ellipses. For example, the string
The quick, brown fox jumped over the lazy "dog." And then ... what happened?
is broken into two sentences.
The quick, brown fox jumped over the lazy "dog." |And then ... what happened?|
Here is an example of how to program with break iterators. As always, you first get a break iterator with a static factory method. You can request one of four iterators to iterate through characters, words, lines, or sentences. Note that once you have a particular iterator object, such as one for sentences, it can iterate only through sentences. More generally, a break iterator can iterate only through the construct for which it was created. For example, the following code lets you analyze individual words:
Locale loc = . . .; BreakIterator wordIter = BreakIterator.getWordInstance(loc);
Once you have an iterator, you give it a string to iterate through.
String msg = " The quick, brown fox"; wordIter.setText(msg);
Then, call the first method to get the offset of the first boundary.
int f = wordIter.first(); // returns 3
In our example, this call to first returns a 3 —which is the offset of the first space inside the string. You keep calling the next method to get the offsets for the next tokens. You know there are no more tokens when a call to next returns the constant BreakIterator.DONE. For example, here is how you can iterate through the remaining word breaks.
int to;
while ((to = currentBreakIterator.next()) !=
BreakIterator.DONE)
{ // do something with to
}
The program in Example 10-4 lets you type text into the text area on the top of the frame. Then, select the way you want to break the text (character, word, line, or sentence). You then see the text boundaries in the text area on the bottom (see Figure 10-4).

1. import java.awt.*;
2. import java.awt.event.*;
3. import java.text.*;
4. import java.util.*;
5. import javax.swing.*;
6.
7. /**
8. This program demonstrates breaking text under
9. various locales.
10. */
11. public class TextBoundaryTest
12. {
13. public static void main(String[] args)
14. {
15. JFrame frame = new TextBoundaryFrame();
16. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. frame.show();
18. }
19. }
20.
21. /**
22. This frame contains radio buttons to select where to break
23. the text, a combo box to pick a locale, a text field area
24. to enter text, and a text area to display the broken text.
25. */
26. class TextBoundaryFrame extends JFrame
27. {
28. public TextBoundaryFrame()
29. {
30. setSize(WIDTH, HEIGHT);
31. setTitle("TextBoundaryTest");
32.
33. ActionListener listener = new
34. ActionListener()
35. {
36. public void actionPerformed(ActionEvent event)
37. {
38. updateDisplay();
39. }
40. };
41.
42. JPanel p = new JPanel();
43. addRadioButton(p, characterRadioButton, rbGroup, listener);
44. addRadioButton(p, wordRadioButton, rbGroup, listener);
45. addRadioButton(p, lineRadioButton, rbGroup, listener);
46. addRadioButton(p, sentenceRadioButton, rbGroup, listener);
47.
48. getContentPane().setLayout(new GridBagLayout());
49. GridBagConstraints gbc = new GridBagConstraints();
50. gbc.fill = GridBagConstraints.NONE;
51. gbc.anchor = GridBagConstraints.EAST;
52. add(new JLabel("Locale"), gbc, 0, 0, 1, 1);
53. gbc.anchor = GridBagConstraints.WEST;
54. add(localeCombo, gbc, 1, 0, 1, 1);
55. add(p, gbc, 0, 1, 2, 1);
56. gbc.fill = GridBagConstraints.BOTH;
57. gbc.weighty = 100;
58. add(new JScrollPane(inputText), gbc, 0, 2, 2, 1);
59. add(new JScrollPane(outputText), gbc, 0, 3, 2, 1);
60.
61. locales = BreakIterator.getAvailableLocales();
62. for (int i = 0; i < locales.length; i++)
63. localeCombo.addItem(locales[i].getDisplayName());
64. localeCombo.setSelectedItem(
65. Locale.getDefault().getDisplayName());
66.
67. localeCombo.addActionListener(listener);
68.
69. inputText.setText("The quick, brown fox jump-ed\n"
70. + "over the lazy \"dog.\" And then...what happened?");
71. updateDisplay();
72. }
73.
74. /**
75. Adds a radio button to a container.
76. @param p the container into which to place the button
77. @param b the button
78. @param g the button group
79. @param listener the button listener
80. */
81. public void addRadioButton(Container p, JRadioButton b,
82. ButtonGroup g, ActionListener listener)
83. {
84. b.setSelected(g.getButtonCount() == 0);
85. b.addActionListener(listener);
86. g.add(b);
87. p.add(b);
88. }
89.
90. /**
91. A convenience method to add a component to given grid bag
92. layout locations.
93. @param c the component to add
94. @param gbc the grid bag constraints to use
95. @param x the x grid position
96. @param y the y grid position
97. @param w the grid width
98. @param h the grid height
99. */
100. public void add(Component c, GridBagConstraints gbc,
101. int x, int y, int w, int h)
102. {
103. gbc.gridx = x;
104. gbc.gridy = y;
105. gbc.gridwidth = w;
106. gbc.gridheight = h;
107. getContentPane().add(c, gbc);
108. }
109.
110. /**
111. Updates the display and breaks the text according
112. to the user settings.
113. */
114. public void updateDisplay()
115. {
116. Locale currentLocale = locales[
117. localeCombo.getSelectedIndex()];
118. BreakIterator currentBreakIterator = null;
119. if (characterRadioButton.isSelected())
120. currentBreakIterator
121. = BreakIterator.getCharacterInstance(currentLocale);
122. else if (wordRadioButton.isSelected())
123. currentBreakIterator
124. = BreakIterator.getWordInstance(currentLocale);
125. else if (lineRadioButton.isSelected())
126. currentBreakIterator
127. = BreakIterator.getLineInstance(currentLocale);
128. else if (sentenceRadioButton.isSelected())
129. currentBreakIterator
130. = BreakIterator.getSentenceInstance(currentLocale);
131.
132. String text = inputText.getText();
133. currentBreakIterator.setText(text);
134. outputText.setText("");
135
136 . int from = currentBreakIterator.first();
137. int to;
138. while ((to = currentBreakIterator.next()) !=
139. BreakIterator.DONE)
140. {
141. outputText.append(text.substring(from, to) + "|");
142. from = to;
143. }
144. outputText.append(text.substring(from));
145. }
146.
147. private Locale[] locales;
148. private BreakIterator currentBreakIterator;
149.
150. private JComboBox localeCombo = new JComboBox();
151. private JTextArea inputText = new JTextArea(6, 40);
152. private JTextArea outputText = new JTextArea(6, 40);
153. private ButtonGroup rbGroup = new ButtonGroup();
154. private JRadioButton characterRadioButton
155. = new JRadioButton("Character");
156. private JRadioButton wordRadioButton
157. = new JRadioButton("Word");
158. private JRadioButton lineRadioButton
159. = new JRadioButton("Line");
160. private JRadioButton sentenceRadioButton
161. = new JRadioButton("Sentence");
162. private static final int WIDTH = 400;
163. private static final int HEIGHT = 400;
164. }
![]()
static Locale[] getAvailableLocales()
returns an array of Locale objects for which BreakIterator objects are available.
static BreakIterator getCharacterInstance()
static BreakIterator getCharacterInstance(Locale l)
static BreakIterator getWordInstance()
static BreakIterator getWordInstance(Locale l)
static BreakIterator getLineInstance()
static BreakIterator getLineInstance(Locale l)
static BreakIterator getSentenceInstance()
static BreakIterator getSentenceInstance(Locale l)
return a break iterator for characters, words, lines, and sentences for the default or the given locale.
void setText(String text)
void setText(CharacterIterator text)
CharacterIterator getText()
set or get the text to be scanned.
int first()
moves the current boundary to the first boundary position in the scanned string and returns the index.
int next()
moves the current boundary to the next boundary position and returns the index. Returns BreakIterator.DONE if the end of the string has been reached.
int previous()
moves the current boundary to the previous boundary position and returns the index. Returns BreakIterator.DONE if the beginning of the string has been reached.
int last()
moves the current boundary to the last boundary position in the scanned string and returns the index.
int current()
returns the index of the current boundary.
int next(int n)
moves the current boundary to the nth boundary position from the current one and returns the index. If n is negative, then the position is set closer to the beginning of the string. Returns BreakIterator.DONE if the end or beginning of the string has been reached.
int following(int pos)
moves the current boundary to the first boundary position after offset pos in the scanned string, and returns the index. The returned value is larger than pos, or it is equal to BreakIterator.DONE.
In the early days of "mail-merge" programs, you had strings like:
"On {2}, a {0} destroyed {1} houses and caused {3} of
damage."
where the numbers in braces were placeholders for actual names and values. This technique is actually very convenient for doing certain kinds of internationalization, and the Java programming language has a convenience MessageFormat class to allow formatting text that has a pattern. To use the class, follow these steps.
Write the pattern as a string. You can use up to 10 placeholders {0}...{9}. You can use each placeholder more than once.
Construct a MessageFormat object with the pattern string as the constructor parameter.
Build an array of objects to substitute for the placeholders. The number inside the braces refers to the index in the array of objects.
Call the format method with the array of objects as a parameter.
CAUTION
![]() |
Steps 1 and 2 build a MessageFormat object that uses the current locale for formatting numbers and dates. If you need to specify a different locale, you must first construct a MessageFormat object with a dummy pattern, then call the setLocale method, and finally call the applyPattern method with the actual pattern that you want to use. MessageFormat format = new MessageFormat("");
format.setLocale(locale);
format.applyPattern(pattern);
|
Here is an example of these steps. We first supply the array of objects for the placeholders.
String pattern =
"On {2}, a {0} destroyed {1} houses and caused {3} of
damage.";
MessageFormat msgFmt = new MessageFormat(pattern);
Object[] msgArgs = {
"hurricane",
new Integer(99),
new GregorianCalendar(1999, 0, 1).getTime(),
new Double(10E7)
};
String msg = msgFmt.format(msgArgs);
System.out.println(msg);
The number of the placeholder refers to the index in the object array. For example, the first placeholder {2} is replaced with msgArgs[2]. Since we need to supply objects, we have to remember to wrap integers and floating-point numbers in their Integer and Double wrappers before passing them. Notice the cumbersome construction of the date that we used. The format method expects an object of type Date, but the Date(int, int, int) constructor is deprecated in favor of the Calendar class. Therefore, we have to create a Calendar object and then call the getTime (sic) method to convert it to a Date object.
This code prints:
On 1/1/99 12:00 AM, a hurricane destroyed 99 houses and caused 100,000,000 of damage.
That is a start, but it is not perfect. We don't want to display the time "12:00 AM," and we want the damage amount printed as a currency value. The way we do this is by supplying an (optional) format for some or all of the placeholders. There are two ways to supply formats:
By adding them to the pattern string;
By calling the setFormat or setFormats method.
Let's do the easy one first. We can set a format for each individual occurrence of a placeholder. In our example, we want the first occurrence of a placeholder (which is placeholder {2}) to be formatted as a date, without a time field. And we want the fourth placeholder to be formatted as a currency. Actually, the placeholders are numbered starting at 0, so we actually want to set the formats of placeholders 0 and 3. We will use the formatters that you saw earlier in this chapter, namely, DateFormat.getDateInstance(loc) and NumberFormat.getCurrencyInstance(loc), where loc is the locale we want to use. Conveniently, all formatters have a common base class Format. The setFormat method of the MessageText class receives an integer, the 0-based count of the placeholder to which the format should be applied, and a Format reference.
To build the format we want, we simply set the formats of placeholders 0 and 3 and then call the format method.
msgFmt.setFormat(0, DateFormat.getDateInstance(DateFormat.LONG, loc)); msgFmt.setFormat(3, NumberFormat.getCurrencyInstance(loc)); String msg = msgFmt.format(msgArgs); System.out.println(msg);
Now, the printout is
On January 1, 1999, a hurricane destroyed 99 houses and caused $100,000,000.00 of damage.
Next, rather than setting the formats individually, we can pack them into an array. Use null if you don't need any special format.
Format argFormats[] =
{
DateFormat.getDateInstance(DateFormat.LONG, loc),
null,
null,
NumberFormat.getCurrencyInstance(loc)
};
msgFmt.setFormats(argFormats);
Note that the msgArgs and the argFormats array entries do not correspond to one another. The msgArgs indexes correspond to the number inside the {} delimiters. The argFormats indexes correspond to the position of the {} delimiters inside the message string. This arrangement sounds cumbersome, but there is a reason for it. It is possible for the placeholders to be repeated in the string, and each occurrence may require a different format. Therefore, the formats must be indexed by position. For example, if the exact time of the disaster was known, we might use the date object twice, once to extract the day and once to extract the time.
String pattern =
"On {2}, a {0} touched down at {2} and destroyed {1}
houses.";
MessageFormat msgFmt = new MessageFormat(pattern);
Format argFormats[] =
{ DateFormat.getDateInstance(DateFormat.LONG, loc),
null,
DateFormat.getTimeInstance(DateFormat.SHORT, loc),
null
};
msg.setFormats(argFormats);
Object[] msgArgs = {
"hurricane",
new Integer(99),
new GregorianCalendar(1999, 0, 1, 11, 45, 0).getTime(),
};
String msg = msgFmt.format(msgArgs);
System.out.println(msg);
This example code prints:
On January 1, 1999, a hurricane touched down at 11:45 AM and destroyed 99 houses.
Note that the placeholder {2} was printed twice, with two different formats!
Rather than setting placeholders dynamically, we can also set them in the message string. For example, here we specify the date and currency formats directly in the message pattern.
"On {2,date,long}, a {0} destroyed {1} houses and caused {3,number,currency} of damage."
If you specify formats directly, you don't need to make a call to setFormat or setFormats. In general, you can make the placeholder index be followed by a type and a style. Separate the index, type, and style by commas. The type can be any of:
number time date choice
If the type is number, then the style can be:
integer currency percent
or it can be a number format pattern such as $,##0. (See Chapter 3 of Volume 1 for a discussion of number format patterns.)
If the type is either time or date, then the style can be:
short medium long full
or a date format pattern. (See the documentation of the SimpleDateFormat class for more information about the possible formats.)
Choice formats are more complex, and we take them up in the next section.
![]()
MessageFormat(String pattern)
constructs a message format object with the specified pattern.
void applyPattern(String pattern)
sets the pattern of a message format object to the specified pattern.
void setLocale(Locale loc)
Locale getLocale()
set or get the locale to be used for the placeholders in the message. The locale is only used for subsequent patterns that you set by calling the applyPattern method.
void setFormats(Format[] formats)
Format[] getFormats()
set or get the formats to be used for the placeholders in the message.
void setFormat(int i, Format format)
sets the formats to be used for the ith placeholder in the message.
String format(String pattern, Object[] args)
formats the objects by using args[i] as input for placeholder {i}.
Let's look closer at the pattern of the preceding section:
"On {2}, a {0} destroyed {1} houses and caused {3} of damage."
If we replace the disaster placeholder {0} with "earthquake", then the sentence is not grammatically correct in English.
On January 1, 1999, a earthquake destroyed . . .
That means what we really want to do is integrate the article "a" into the placeholder:
"On {2}, {0} destroyed {1} houses and caused {3} of damage."
Then, the {0} would be replaced with "a hurricane" or "an earthquake". That is especially appropriate if this message needs to be translated into a language where the gender of a word affects the article. For example, in German, the pattern would be
"{0} zerstörte am {2} {1} Häuser und richtete einen Schaden von
{3} an."
The placeholder would then be replaced with the grammatically correct combination of article and noun, such as "Ein Wirbelsturm", "Eine Naturkatastrophe".
Now let us turn to the {1} parameter. If the disaster isn't all that catastrophic, then {1} might be replaced with the number 1, and the message would read:
On January 1, 1999, a mudslide destroyed 1 houses and . . .
We would ideally like the message to vary according to the placeholder value, so that it can read
no houses one house 2 houses . . .
depending on the placeholder value. The ChoiceFormat class was designed to let you do this. A ChoiceFormat object is constructed with two arrays:
An array of limits
An array of format strings
double[] limits = . . .; String[] formatStrings = . . .; ChoiceFormat choiceFmt = new ChoiceFormat(limits, formatStrings); double input = . . .; String s = choiceFmt.format(input);
The limits and formatStrings arrays must have the same length. The numbers in the limits array must be in ascending order. Then, the format method checks between which limits the input falls. If
limits[i] <= input && input < limits[i + 1]
then formatStrings[i] is used to format the input. If the input is at least as large as the last limit, then the last format string is used. And, if the input is less than limits[0], then formatStrings[0] is used anyway.
For example, consider these limits and format strings:
double[] limits = {0, 1, 2};
String[] formatStrings = {"no houses", "one house", "many
houses"};
Table 10-4 shows the return values of the call to
String selected = choiceFmt.format(input);
| input | selected |
|---|---|
| input < 0 | "no houses" |
| 0 <= input && input < 1 | "no houses" |
| 1 <= input && input < 2 | "one house" |
| 2 <= input | "many houses" |
NOTE
![]() |
This example shows that the designer of the ChoiceFormat class was a bit muddleheaded. If you have three strings, you need two limits to separate them. In general, you need one fewer limit than you have strings. Thus, the first limit is meaningless, and you can simply set the first and second limit to the same number. For example, the following code works fine: double[] limits = {1, 1, 2};
String[] formatStrings = {"no houses", "one house", "many
houses"};
ChoiceFormat choiceFmt = new ChoiceFormat(limits,
formatStrings);
|
Of course, in our case, we don't want to return "many houses" if the number of houses is 2 or greater. We still want the value to be formatted. Here is the code to format the value.
double[] limits = {0, 1, 2};
String[] formatStrings = {"no houses", "one house", "{1}
houses"};
ChoiceFormat choiceFmt = new ChoiceFormat(limits,
formatStrings);
msgFmt.setFormat(2, choiceFmt);
That is, we create the choice format object and set it as the format to use for the third placeholder (because the count is 0-based).
Why do we use {1} in the format string? The usage is a little mysterious. When the message format applies the choice format on the placeholder, the choice format returns "{1} houses". That string is then formatted again by the message format, and the answer is spliced into the result. As a rule, you should always feed back the same placeholder that was used to make the choice. Otherwise, you can create weird effects.
You can add formatting information to the returned string, for example,
String[] formatStrings
= {"no houses", "one house", "{1, number, integer} houses"};
As you saw in the preceding section, it is also possible to express the choice format directly in a format string. When the format type is choice, then the next parameter is a list of pairs, each pair consisting of a limit and a format string, separated by a #. The pairs themselves are separated by |. Here is how to express the house format:
{1,choice,0#no houses|1#one house|2#{1} houses}
Thus, there are three sets of choices:
0#no houses
1#one house
2#{1} houses
The first one is used if the placeholder value is < 1, the second is used if the value is at least 1 but < 2, and the third is used if the value is at least 2.
NOTE
![]() |
As previously noted, the first limit is meaningless. But here you can't set the first and second limits to the same value; the format parser complains that 1#no houses|1#one house|2#{1} houses
is an invalid choice. In this case, you must set the
first limit to any number that is strictly less than the second limit. You
can safely use - The syntax would have been a lot clearer if the designer of this class realized that the limits belong between the choices, such as no houses|1|one house|2|{1} houses
// not the actual format
|
You can use the < symbol to denote that a choice should be selected if the left bound is strictly less than the right bound.
The < symbol is translated into a limit that is the next floating point number after the number specified in the choice string. There is even a static method ChoiceFormat.nextDouble to compute that number.
You can also use the
symbol (expressed as the
Unicode character code \u2264) as a synonym for #.
For example,
{0,choice,-\u221E<negative|0\u2264zero|0<positive}
or
{0,choice,-
<negative|0
zero|0<positive}
yields the following strings:
negative if -
input and input < 0:
zero if 0
input and input <
ChoiceFormat.nextDouble(0)
positive if ChoiceFormat.nextDouble(0)
input
Let's return to our natural disaster scenario. If we put the choice string inside the original message string, then we get the rather monstrous format instruction:
String pattern =
"On {2,date,long}, {0} destroyed {1,choice,0#no houses|1#one
house|2#{1} houses}
and caused {3,number,currency} of damage.";
Or, in German,
String pattern =
"{0} zerstörte am {2,date,long} {1,choice,0#kein Haus|1#ein
Haus|2#{1} Häuser}
und richtete einen Schaden von {3,number,currency} an.";
Note that the ordering of the words is different in German, but the array of objects you pass to the format method is the same. The order of the placeholders in the format string takes care of the changes in the word ordering.
![]()
ChoiceFormat(String pattern)
constructs a choice format from a pattern string containing a | delimited set of pairs, each of which is of the form limit#formatString.
ChoiceFormat(double limits[], String formatStrings[])
constructs a choice format with the given limits and formats. The limits must be increasing. If input is the value to be formatted, then it is formatted with the formatString[i], where i is the smallest index such that limits[i] <= input. However, all inputs that are less than limits[1] are formatted with formatString[0].
static double nextDouble(double x)
returns the smallest double-precision floating-point number that is strictly greater than x. For example, nextDouble(0) is 4.9E-324.
As you know, the Java programming language itself is fully Unicode-based. However, operating systems typically have their own, homegrown, often incompatible character encoding, such as ISO 8859 -1 (an 8 -bit code sometimes called the "ANSI" code) in the United States, or BIG5 in Taiwan. So, the input that you receive from a user might be in a different encoding system, and the strings that you show to the user must eventually be encoded in a way that the local operating system understands.
Of course, inside your program, you should always use Unicode characters. You have to hope that the implementation of the Java virtual machine on that platform successfully converts input and output between Unicode and the local character set. For example, if you set a button label, you specify the string in Unicode, and it is up to the Java virtual machine to get the button to display your string correctly. Similarly, when you call getText to get user input from a text box, you get the string in Unicode, no matter how the user entered it.
However, you need to be careful with text files. Never read a text file one byte at a time! Always use the InputStreamReader or FileReader classes that were described in Volume 1, Chapter 12. These classes automatically convert from a particular character encoding to Unicode. By default, they use the local encoding scheme, but as you saw in Volume 1, Chapter 12, you can specify the encoding in the constructor of the InputStreamReader class, for example,
InputStreamReader in = new InputStreamReader(in, "8859_1");
Unfortunately, there is currently no connection between locales and character encodings. For example, if your user has selected the Chinese Traditional locale zh_TW, there is no method in the Java programming language that tells you that the BIG5 character encoding would be the most appropriate.
When writing text files, you need to decide:
Is the output of the text file intended for humans to read or for use with other programs on their local machines?
Is the output simply going to be fed into the same or another program?
If the output is intended for human consumption or a non-Unicode-enabled program, you'll need to convert it to the local character encoding by using a PrintWriter, as you saw in Volume 1, Chapter 12. Otherwise, just use the writeUTF method of the DataOutputStream to write the string in Unicode Text Format. Then, of course, the program reading the file must open it as a DataInputStream, and must read the string with the readUTF method.
TIP
![]() |
In the case of input to a program in the Java programming language, an even better choice is to use serialization. Then, you never have to worry at all how strings are saved and loaded. |
Of course, with both data streams and object streams, the output will not be in human-readable form.
It is worth keeping in mind that you, the programmer, will need to communicate with the Java compiler. And you do that with tools on your local system. For example, you can use the Chinese version of Notepad to write your Java source code files. The resulting source code files are not portable because they use the local character encoding (GB or BIG5, depending on which Chinese operating system you use). Only the compiled class files are portable—they will automatically use the UTF encoding for identifiers and strings. That means that even when a program is compiling and running, three character encodings are involved:
Source files: local encoding
Class files: UTF
Virtual machine: Unicode
To make your source files portable, restrict yourself to using the plain ASCII encoding. That is, you should change all non-ASCII characters to their equivalent Unicode encodings. For example, rather than using the string "Häuser", use "H\u0084user". The SDK contains a utility, native2ascii, that you can use to convert the native character encoding to plain ASCII. This utility simply replaces every non-ASCII character in the input with a \u followed by the four hex digits of the Unicode value. To use the native2ascii program, simply provide the input and output file names.
native2ascii Myfile.java Myfile.temp
You can convert the other way with the -reverse option:
native2ascii -reverse Myfile.java Myfile.temp
And you can specify another encoding with the -encoding option. The encoding name must be one of those listed in the encodings table in Chapter 12 of volume 1.
native2ascii -encoding Cp437 Myfile.java Myfile.temp
Finally, we strongly recommend that you restrict yourself to plain ASCII class names. Since the name of the class also turns into the name of the class file, you are at the mercy of the local file system to handle any non-ASCII coded names—and it will almost certainly not do it right. For example, depressingly enough, Windows 95 uses yet another character encoding, the so-called Code Page 437 or original PC encoding, for its file names. Windows 95 makes a valiant attempt to translate between ANSI and original names, but the JVM class loader does not. (NT is much better this way.) For example, if you make a class Bär, then the JDK class loader will complain that it "cannot find class BSr." There is a reason for this behavior, but you don't want to know. Simply stick to ASCII for your class names until all computers around the world offer consistent support for Unicode.
When localizing an application, you'll probably have a dauntingly large number of message strings, button labels, and so on, that all need to be translated. To make this task feasible, you'll want to define the message strings in an external location, usually called a resource. The person carrying out the translation can then simply edit the resource files without having to touch the source code of the program.
NOTE
![]() |
Java technology resources are not the same as Windows or Macintosh resources. A Windows executable program stores resources such as menus, dialog boxes, icons, and messages in a section separate from the program code. A resource editor can be used to inspect and update these resources without affecting the program code. |
Java technology, unfortunately, does not have a mechanism for storing external resources in text files. Instead, all resource data must be put in a class, either as static variables or as return values of method calls. You create a different class for each locale, and then the getBundle method of the ResourceBundle class automatically locates the correct class for your locale.
NOTE
![]() |
Chapter 10 of Volume 1 describes a concept of file resources, where data files, sounds, and images can be placed in a JAR file. The getResource method of the class Class finds the file, opens it, and returns a URL to the resource. Why? When you write a program that needs access to files, it needs to find the files. By placing the files into the JAR file, you leave the job of finding the files to the class loader, which already knows how to locate the class files. While this mechanism does not directly support internationalization, it is useful for locating localized property files, and we take advantage of it in the next section. |
When localizing an application, you need to make a set of classes that describe the locale-specific items (such as messages, labels, and so on) for each locale that you want to support. Each of these classes must extend the class ResourceBundle. (You'll see a little later the details involved in designing these kinds of classes.) You also need to use a naming convention for these classes, where the name of the class corresponds to the locale. For example, resources specific for Germany go to the class ProgramResources_de_DE, while those that are shared by all German-speaking countries go into ProgramResources_de. Taiwan-specific resources go into ProgramResources_zh_TW, and any Chinese language strings go into ProgramResources_zh. In general, use
ProgramResources_language_country
for all country-specific resources, and use
ProgramResources_language
for all language-specific resources. Finally, as a fallback, you can put the U.S. English strings and messages into the class ProgramResources, without any suffix. Then, compile all these classes and store them with the other application classes for the project.
Once you have a class for the resource bundle, you load it with the command
ResourceBundle currentResources =
ResourceBundle.getBundle("ProgramResources", currentLocale);
The getBundle method attempts to load the class that matches the current locale by language, country, and variant. If it is not successful, then the variant, country, and language are dropped in turn. That is, the getBundle method tries to load one of the following classes until it is successful.
ProgramResources_language_country_variant ProgramResources_language_country ProgramResources_language ProgramResources
If all these attempts are unsuccessful, then the getBundle method tries all over again, only this time it uses the default locale instead of the current locale. If even these attempts fail, the method throws a MissingResourceException.
Once the getBundle method has located a class, say, ProgramResources_de_DE, it will still keep looking for ProgramResources_de and ProgramResources. If these classes exist, they become the parents of the ProgramResources_de_DE class in a resource hierarchy. Later, when looking up a resource, the getObject method will search the parents if the lookup was not successful in the current class. That is, if a particular resource was not found in ProgramResources_de_DE, then the ProgramResources_de and ProgramResources will be queried as well.
This is clearly a very useful service and one that would be tedious to program by hand. A resource mechanism of the Java programming language lets you locate the class that is the best match for localization information. It is very easy to add more and more localizations to an existing program: all you have to do is add additional resource classes.
Now that you know how a program can locate the correct resource, we show you how to place the language-dependent information into the resource class. Ultimately, it would be nice if you could get tools that even a nonprogrammer could use to define and modify resources. We hope and expect that developers of integrated Java programming environments will eventually provide such tools. But right now, creating resources still involves some programming. We take that up next.
In the Java programming language, you place resources inside classes that extend the ResourceBundle class. Each resource bundle implements a lookup table. When you design a program, you provide a key string for each setting you want to localize, and you use that key string to retrieve the setting. Use getString to retrieve a string resource.
String computeButtonLabel
= resources.getString("computeButton");
However, a resource bundle can store objects of any kind. Not all localized settings are strings! You use the getObject method to retrieve arbitrary objects from the bundle.
Color backgroundColor
= (Color)resources.getObject("backgroundColor");
double[] paperSize
= (double[])resources.getObject("defaultPaperSize");
TIP
![]() |
You do not need to place all resources for your application into a single bundle. You could have one bundle for button labels, one for error messages, and so on. |
To implement your own resource bundle class, you need to implement two methods:
Enumeration getKeys() Object handleGetObject(String key)
The getObject and getString methods call the handleGetObject method that you supply. For example, you can write the following classes to provide German and U.S. English resources.
public class ProgramResources extends ResourceBundle
// place getKeys method in common superclass
{
public Enumeration getKeys()
{
return Collections.enumeration(Arrays.asList(keys));
}
private String[] keys = { "computeButton", "backgroundColor",
"defaultPaperSize" };
}
public class ProgramResources_de extends ProgramResources{
{
public Object handleGetObject(String key)
{
if (key.equals("computeButton"))
return "Rechnen";
else if (key.equals("backgroundColor")
return Color.black;
else if (key.equals("defaultPaperSize")
return new double[] { 210, 297 };
}
}
public class ProgramResources_en_US extends ProgramResources{
{
public Object handleGetObject(String key)
{
if (key.equals("computeButton"))
return "Compute";
else if (key.equals("backgroundColor")
return Color.blue;
else if (key.equals("defaultPaperSize")
return new double[] { 216, 279 };
}
}
NOTE
![]() |
Everyone on the planet, with the exception of the United States and Canada, uses ISO 216 paper sizes. For more information, see http://www.cl.cam.ac.uk/~mgk25/iso-paper.html. According to the U.S. Metric Association (http://lamar.colostate.edu/~hillger), there are only three countries in the world that have not yet officially adopted the metric system, namely, Liberia, Myanmar (Burma), and the United States of America. U.S. businesses that wish to extend their export market further need to go metric. See http://ts.nist.gov/ts/htdocs/200/202/mpo_reso.htm for a useful set of links to information about the metric (SI) system. |
Of course, it is extremely tedious to write this kind of code for every resource bundle. The Java standard library provides two convenience classes, ListResourceBundle and PropertyResourceBundle, to make the job easier.
The ListResourceBundle lets you place all your resources into an object array, and then it does the lookup for you. You need to supply the following skeleton:
public class ProgramResources_language_country
extends ListResourceBundle
{
public Object[][] getContents() { return contents; }
private static final Object[][] contents =
{
// localization information goes here
}
}
For example,
public class ProgramResources_de
extends ListResourceBundle
{
public Object[][] getContents() { return contents; }
private static final Object[][] contents =
{
{ "computeButton", "Rechnen" },
{ "backgroundColor", Color.black },
{ "defaultPaperSize", new double[] { 210, 297 } }
}
}
public class ProgramResources_en_US
extends ListResourceBundle
{
public Object[][] getContents() { return contents; }
private static final Object[][] contents =
{
{ "computeButton", "Compute" },
{ "backgroundColor", Color.blue },
{ "defaultPaperSize", new double[] { 216, 279 } }
}
}
Note that you need not supply the getObject lookup method. The Java library provides it in the superclass ListResourceBundle.
As an alternative, if all your settings are strings, you can use the more convenient PropertyResourceBundle mechanism. You place all your strings into a property file, as described in Chapter 2. This is simply a text file with one key/value pair per line. A typical file would look like this:
computeButton=Rechnen backgroundColor=black defaultPaperSize=210x297
Then you name your property files according to the following pattern:
ProgramStrings.properties ProgramStrings_en.properties ProgramStrings_de_DE.properties
You can load the resources simply as
ResourceBundle bundle
= ResourceBundle.getBundle("ProgramStrings", locale);
The getBundle locates the appropriate property file and turns it into a PropertyResourceBundle. You never work with the PropertyResourceBundle class directly.
Placing all resources into a text file is enormously attractive. It is much easier for the person performing the localization, especially if he or she is not familiar with the Java programming language, to understand a text file than a file with code. The downside is that your program must parse strings (such as the paper size "210x297" in the example above.) The best solution is, therefore, to put the string resources into property files and use a ListResourceBundle for those resource objects that are not strings.
CAUTION
![]() |
Files for storing properties are always 7-bit ASCII files. If you need to place Unicode characters into a properties file, you need to encode them by using the \uxxxx encoding. For example, to specify "colorName=Grün", use colorName=Gr\u00FCn You can use the native2ascii tool to generate these files. |
NOTE
![]() |
In this section, you saw how to create resource bundles programmatically. Of course, a lot of the code is completely routine. The Java Internationalization and Localization Toolkit (http://java.sun.com/products/jilkit) is a tool that can help you manage the creation and maintenance of resource bundles. |
![]()
static ResourceBundle getBundle(String baseName, Locale loc)
static ResourceBundle getBundle(String baseName)
load the resource bundle class with the given name, for the given locale or the default locale, and its parent classes. If the resource bundle classes are located in a package, then the base name must contain the full package name, such as "intl.ProgramResources". The resource bundle classes must be public so that the getBundle method can access them.
Object getObject(String name)
looks up an object from the resource bundle or its parents.
String getString(String name)
looks up an object from the resource bundle or its parents and casts it as a string.
String[] getStringArray(String name)
looks up an object from the resource bundle or its parents and casts it as a string array.
Enumeration getKeys()
returns an enumeration object to enumerate the keys of this resource bundle. It enumerates the keys in the parent bundles as well.
We have spent a lot of time showing you how to localize your applications. Now, we explain how localization requires you to change the kind of code you write. For example, you have to be much more careful how you code your event handlers for user interface events. Consider the following common style of programming:
public class MyApplet extends JApplet
implements ActionListener
{
public void init()
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
. . .
}
public void actionPerformed(ActionEvent evt)
{
String arg = evt.getActionCommand();
if (arg.equals("Cancel"))
doCancel();
else . . .
}
. . .
}
Many programmers write this kind of code, and it works fine as long as you never internationalize the interface. However, when the button name is translated to German, "Cancel" turns into "Abbrechen." Then, the name needs to be updated automatically in both the init method and the actionPerformed method. This is clearly error prone—it is a well-known corollary to Murphy's law in computer science that two entities that are supposed to stay in sync, won't. In this case, if you forget to update one of the occurrences of the string, then the button won't work. There are three ways you can eliminate this potential problem.
Use inner classes instead of separate actionPerformed procedures.
Identify components by their reference, not their label.
Use the name attribute to identify components.
Let us look at these three strategies one by one.
Rather than having one handler that handles many actions, you can easily define a separate handler for every component. For example,
public class MyApplet extends JApplet implements ActionListener
{
public void init()
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent e)
{
doCancel();
}
});
. . .
}
. . .
}
This code creates an inner class that listens just to the Cancel button. Since the button and its listener are now tightly joined, there is no more code to parse the button label. Hence, there is only one occurrence of the label string to localize.
We think this is the best solution to the problem of joining a user interface component and its associated handler code. You may not like inner classes, either because they are confusing to read or because each inner class results in an additional class file. The next choice, therefore, is to make the button into an instance variable and compare its reference against the source of the command.
public class MyApplet extends JApplet implements ActionListener
{
public void init()
{
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
. . .
}
public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
if (source == cancelButton)
doCancel();
else . . .
}
. . .
private JButton cancelButton;
}
This approach works fine too. Note that now every user interface element must be stored in an instance variable, and the actionPerformed method must have access to the variables.
Finally, you can give any class that inherits from Component (such as the Button class) a name property. This name may or may not be distinct from its label in a specific locale, but this is irrelevant; the name property stays constant regardless of locale changes. For example, if you give a cancel button the name "cancel1", this is not a visual attribute of the button, it is simply a text string associated with the button. (Think of it as a property of the button—see Chapter 8 for more on properties.) When an action event is triggered, you first get the source and then you can find the name attribute of the source.
public class MyApplet extends JApplet implements ActionListener
{
public void init()
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setName("cancel1");
cancelButton.addActionListener(this);
. . .
}
public void actionPerformed(ActionEvent evt)
{
Component source = (Component)evt.getSource();
if (source.getName().equals("cancel1"))
doCancel();
. . .
}
. . .
}
![]()
void setName(String s)
String getName()
set or get a component name, an arbitrary tag associated with the component.
In this section, we apply the material from this chapter to localize a retirement calculator applet.
The applet calculates whether or not you are saving enough money for your retirement. You enter your age, how much money you save every month, and so on (see Figure 10-5).

The text area and the graph show the balance of the retirement account for every year. If the numbers turn negative toward the later part of your life and the bars in the graph show up below the x-axis, you need to do something; for example, save more money, postpone your retirement, die earlier, or be younger.
The retirement calculator now works in three locales (English, German, and Chinese). Here are some of the highlights of the internationalization.
The labels, buttons, and messages are translated into German and Chinese. You can find them in the classes RetireResources_de, RetireResources_zh. English is used as the fallback—see the RetireResources file. To generate the Chinese messages, we first typed the file, using Notepad running in Chinese Windows, and then we used the native2ascii utility to convert the characters to Unicode.
Whenever the locale changes, we reset the labels and reformat the contents of the text fields.
The text fields handle numbers, currency amounts, and percentages in the local format.
The computation field uses a MessageFormat. The format string is stored in the resource bundle of each language.
Just to show that it can be done, we use different colors for the bar graph, depending on the language chosen by the user.
Examples 10-5 through 10-8 show the code. Examples 10-9 through 10-11 are the property files for the localized strings. Figures 10-6 and 10-7 show the outputs in German and Chinese. To see Chinese characters, you need to run the applet under Chinese Windows or manually install the Chinese fonts. Otherwise, all Chinese characters show up as "missing character" icons.


NOTE
![]() |
This applet was harder to write than a typical localized application because the user can change the locale on-the-fly. The applet, therefore, had to be prepared to redraw itself whenever the user selects another locale. If you simply want to display your applet in the user's default locale, you will not need to work so hard. You can simply call getLocale() to find the locale of your user's system, and then use it for the entire duration of the applet. |
In sum, while the localization mechanism of the Java programming language still has some rough edges, it does have one major virtue. Once you have organized your application for localization, it is extremely easy to add more localized versions. You simply provide more resource files, and they will be automatically loaded when a user wants them.
1..import java.awt.*;
2. import java.awt.event.*;
3. import java.awt.geom.*;
4. import java.applet.*;
5. import java.util.*;
6. import java.text.*;
7. import java.io.*;
8. import javax.swing.*;
9.
10. /**
11. This applet shows a retirement calculator. The UI is displayed
12. in English, German, and Chinese.
13. */
14. public class Retire extends JApplet
15. {
16. public void init()
17. {
18. GridBagLayout gbl = new GridBagLayout();
19. getContentPane().setLayout(gbl);
20.
21. GridBagConstraints gbc = new GridBagConstraints();
22. gbc.weightx = 100;
23. gbc.weighty = 0;
24.
25. gbc.fill = GridBagConstraints.NONE;
26. gbc.anchor = GridBagConstraints.EAST;
27. add(languageLabel, gbc, 0, 0, 1, 1);
28. add(savingsLabel, gbc, 0, 1, 1, 1);
29. add(contribLabel, gbc, 2, 1, 1, 1);
30. add(incomeLabel, gbc, 4, 1, 1, 1);
31. add(currentAgeLabel, gbc, 0, 2, 1, 1);
32. add(retireAgeLabel, gbc, 2, 2, 1, 1);
33. add(deathAgeLabel, gbc, 4, 2, 1, 1);
34. add(inflationPercentLabel, gbc, 0, 3, 1, 1);
35. add(investPercentLabel, gbc, 2, 3, 1, 1);
36.
37. gbc.fill = GridBagConstraints.HORIZONTAL;
38. gbc.anchor = GridBagConstraints.WEST;
39. add(localeCombo, gbc, 1, 0, 2, 1);
40. add(savingsField, gbc, 1, 1, 1, 1);
41. add(contribField, gbc, 3, 1, 1, 1);
42. add(incomeField, gbc, 5, 1, 1, 1);
43. add(currentAgeField, gbc, 1, 2, 1, 1);
44. add(retireAgeField, gbc, 3, 2, 1, 1);
45. add(deathAgeField, gbc, 5, 2, 1, 1);
46. add(inflationPercentField, gbc, 1, 3, 1, 1);
47. add(investPercentField, gbc, 3, 3, 1, 1);
48.
49. computeButton.setName("computeButton");
50. computeButton.addActionListener(new
51. ActionListener()
52. {
53. public void actionPerformed(ActionEvent event)
54. {
55. getInfo();
56. updateData();
57. updateGraph();
58. }
59. });
60. add(computeButton, gbc, 5, 3, 1, 1);
61.
62. gbc.weighty = 100;
63. gbc.fill = GridBagConstraints.BOTH;
64. add(retireCanvas, gbc, 0, 4, 4, 1);
65. add(new JScrollPane(retireText), gbc, 4, 4, 2, 1);
66. retireText.setEditable(false);
67. retireText.setFont(new Font("Monospaced", Font.PLAIN, 10));
68.
69. info.setSavings(0);
70. info.setContrib(9000);
71. info.setIncome(60000);
72. info.setCurrentAge(35);
73. info.setRetireAge(65);
74. info.setDeathAge(85);
75. info.setInvestPercent(0.1);
76. info.setInflationPercent(0.05);
77.
78. localeCombo.addActionListener(new
79. ActionListener()
80. {
81. public void actionPerformed(ActionEvent event)
82. {
83. setCurrentLocale(
84. locales[localeCombo.getSelectedIndex()]);
85. }
86. });
87.
88. locales = new Locale[]
89. { Locale.US, Locale.CHINA, Locale.GERMANY };
90.
91. int localeIndex = 0; // US locale is default selection
92.
93. for (int i = 0; i < locales.length; i++)
94. // if current locale one of the choices, we'll select it
95. if (getLocale().equals(locales[i])) localeIndex = i;
96.
97. setCurrentLocale(locales[localeIndex]);
98. }
99.
100. /**
101. A convenience method to add a component to given grid bag
102. layout locations.
103. @param c the component to add
104. @param gbc the grid bag constraints to use
105. @param x the x grid position
106. @param y the y grid position
107. @param w the grid width
108. @param h the grid height
109. */
110. public void add(Component c, GridBagConstraints gbc,
111. int x, int y, int w, int h)
112. {
113. gbc.gridx = x;
114. gbc.gridy = y;
115. gbc.gridwidth = w;
116. gbc.gridheight = h;
117. getContentPane().add(c, gbc);
118. }
119.
120. /**
121. Sets the current locale.
122. @param locale the desired locale
123. */
124. public void setCurrentLocale(Locale locale)
125. {
126. currentLocale = locale;
127.
128. int localeIndex = localeCombo.getSelectedIndex();
129. localeCombo.removeAllItems();
130. for (int i = 0; i < locales.length; i++)
131. {
132. String language
133. = locales[i].getDisplayLanguage(currentLocale);
134. localeCombo.addItem(language);
135. }
136. if (localeIndex >= 0)
137. localeCombo.setSelectedIndex(localeIndex);
138.
139. res = ResourceBundle.getBundle("RetireResources",
140. currentLocale);
141. resStrings = ResourceBundle.getBundle("RetireStrings",
142. currentLocale);
143. currencyFmt
144. = NumberFormat.getCurrencyInstance(currentLocale);
145. numberFmt
146. = NumberFormat.getNumberInstance(currentLocale);
147. percentFmt
148. = NumberFormat.getPercentInstance(currentLocale);
149.
150. updateDisplay();
151. updateInfo();
152. updateData();
153. updateGraph();
154. }
155.
156. /**
157. Updates all labels in the display.
158. */
159. public void updateDisplay()
160. {
161. languageLabel.setText(resStrings.getString("language"));
162. savingsLabel.setText(resStrings.getString("savings"));
163. contribLabel.setText(resStrings.getString("contrib"));
164. incomeLabel.setText(resStrings.getString("income"));
165. currentAgeLabel.setText(
166. resStrings.getString("currentAge"));
167. retireAgeLabel.setText(resStrings.getString("retireAge"));
168. deathAgeLabel.setText(resStrings.getString("deathAge"));
169. inflationPercentLabel.setText(
170. resStrings.getString("inflationPercent"));
171. investPercentLabel.setText(
172. resStrings.getString("investPercent"));
173. computeButton.setText(
174. resStrings.getString("computeButton"));
175.
176. validate();
177. }
178.
179. /**
180. Updates the information in the text fields.
181. */
182. public void updateInfo()
183. {
184. savingsField.setText(
185. currencyFmt.format(info.getSavings()));
186. contribField.setText(
187. currencyFmt.format(info.getContrib()));
188. incomeField.setText(currencyFmt.format(info.getIncome()));
189. currentAgeField.setText(
190. numberFmt.format(info.getCurrentAge()));
191. retireAgeField.setText(
192. numberFmt.format(info.getRetireAge()));
193. deathAgeField.setText(
194. numberFmt.format(info.getDeathAge()));
195. investPercentField.setText(
196. percentFmt.format(info.getInvestPercent()));
197. inflationPercentField.setText(
198. percentFmt.format(info.getInflationPercent()));
199. }
200.
201. /**
202. Updates the data displayed in the text area.
203. */
204. public void updateData()
205. {
206. retireText.setText("");
207. MessageFormat retireMsg = new MessageFormat("");
208. retireMsg.setLocale(currentLocale);
209. retireMsg.applyPattern(resStrings.getString("retire"));
210.
211. for (int i = info.getCurrentAge();
212. i <= info.getDeathAge(); i++)
213. {
214. Object[] args = { new Integer(i),
215. new Double(info.getBalance(i)) };
216. retireText.append(retireMsg.format(args) + "\n");
217. }
218. }
219.
220. /**
221. Updates the graph.
222. */
223. public void updateGraph()
224. {
225. retireCanvas.setColorPre(
226. (Color)res.getObject("colorPre"));
227. retireCanvas.setColorGain(
228. (Color)res.getObject("colorGain"));
229. retireCanvas.setColorLoss(
230. (Color)res.getObject("colorLoss"));
231. retireCanvas.setInfo(info);
232. repaint();
233. }
234.
235. /**
236. Reads the user input from the text fields.
237. */
238. public void getInfo()
239. {
240. try
241. {
242. info.setSavings(currencyFmt.parse(
243. savingsField.getText()).doubleValue());
244. info.setContrib(currencyFmt.parse(
245. contribField.getText()).doubleValue());
246. info.setIncome(currencyFmt.parse(
247. incomeField.getText()).doubleValue());
248. info.setCurrentAge(numberFmt.parse(
249. currentAgeField.getText()).intValue());
250. info.setRetireAge(numberFmt.parse(
251. retireAgeField.getText()).intValue());
252. info.setDeathAge(numberFmt.parse(
253. deathAgeField.getText()).intValue());
254. info.setInvestPercent(percentFmt.parse(
255. investPercentField.getText()).doubleValue());
256. info.setInflationPercent(percentFmt.parse(
257. inflationPercentField.getText()).doubleValue());
258. }
259. catch (ParseException exception)
260. {
261. }
262. }
263.
264. private JTextField savingsField = new JTextField(10);
265. private JTextField contribField = new JTextField(10);
266. private JTextField incomeField = new JTextField(10);
267. private JTextField currentAgeField = new JTextField(4);
268. private JTextField retireAgeField = new JTextField(4);
269. private JTextField deathAgeField = new JTextField(4);
270. private JTextField inflationPercentField = new JTextField(6);
271. private JTextField investPercentField = new JTextField(6);
272. private JTextArea retireText = new JTextArea(10, 25);
273. private RetireCanvas retireCanvas = new RetireCanvas();
274. private JButton computeButton = new JButton();
275. private JLabel languageLabel = new JLabel();
276. private JLabel savingsLabel = new JLabel();
277. private JLabel contribLabel = new JLabel();
278. private JLabel incomeLabel = new JLabel();
279. private JLabel currentAgeLabel = new JLabel();
280. private JLabel retireAgeLabel = new JLabel();
281. private JLabel deathAgeLabel = new JLabel();
282. private JLabel inflationPercentLabel = new JLabel();
283. private JLabel investPercentLabel = new JLabel();
284.
285. private RetireInfo info = new RetireInfo();
286.
287. private Locale[] locales;
288. private Locale currentLocale;
289. private JComboBox localeCombo = new JComboBox();
290. private ResourceBundle res;
291. private ResourceBundle resStrings;
292. private NumberFormat currencyFmt;
293. private NumberFormat numberFmt;
294. private NumberFormat percentFmt;
295. }
296.
297. /**
298. The information required to compute retirement income data.
299. */
300. class RetireInfo
301. {
302. /**
303. Gets the available balance for a given year.
304. @param year the year for which to compute the balance
305. @return the amount of money available (or required) in
306. that year
307. */
308. public double getBalance(int year)
309. {
310. if (year < currentAge) return 0;
311. else if (year == currentAge)
312. {
313. age = year;
314. balance = savings;
315. return balance;
316. }
317. else if (year == age)
318. return balance;
319. if (year != age + 1)
320. getBalance(year - 1);
321. age = year;
322. if (age < retireAge)
323. balance += contrib;
324. else
325. balance -= income;
326. balance = balance
327. * (1 + (investPercent - inflationPercent));
328. return balance;
329. }
330.
331. /**
332. Gets the amount of prior savings.
333. @return the savings amount
334. */
335. public double getSavings()
336. {
337. return savings;
338. }
339.
340. /**
341. Sets the amount of prior savings.
342. @param x the savings amount
343. */
344. public void setSavings(double x)
345. {
346. savings = x;
347. }
348.
349. /**
350. Gets the annual contribution to the retirement account.
351. @return the contribution amount
352. */
353. public double getContrib()
354. {
355. return contrib;
356. }
357.
358. /**
359. Sets the annual contribution to the retirement account.
360. @param x the contribution amount
361. */
362. public void setContrib(double x)
363. {
364. contrib = x;
365. }
366.
367. /**
368. Gets the annual income.
369. @return the income amount
370. */
371. public double getIncome()
372. {
373. return income;
374. }
375.
376. /**
377. Sets the annual income.
378. @param x the income amount
379. */
380. public void setIncome(double x)
381. {
382. income = x;
383. }
384.
385. /**
386. Gets the current age.
387. @return the age
388. */
389. public int getCurrentAge()
390. {
391. return currentAge;
392. }
393.
394. /**
395. Sets the current age.
396. @param x the age
397. */
398. public void setCurrentAge(int x)
399. {
400. currentAge = x;
401. }
402.
403. /**
404. Gets the desired retirement age.
405. @return the age
406. */
407. public int getRetireAge()
408. {
409. return retireAge;
410. }
411.
412. /**
413. Sets the desired retirement age.
414. @param x the age
415. */
416. public void setRetireAge(int x)
417. {
418. retireAge = x;
419. }
420.
421. /**
422. Gets the expected age of death.
423. @return the age
424. */
425. public int getDeathAge()
426. {
427. return deathAge;
428. }
429.
430. /**
431. Sets the expected age of death.
432. @param x the age
433. */
434. public void setDeathAge(int x)
435. {
436. deathAge = x;
437. }
438.
439. /**
440. Gets the estimated percentage of inflation.
441. @return the percentage
442. */
443. public double getInflationPercent()
444. {
445. return inflationPercent;
446. }
447.
448. /**
449. Sets the estimated percentage of inflation.
450. @param x the percentage
451. */
452. public void setInflationPercent(double x)
453. {
454. inflationPercent = x;
455. }
456.
457. /**
458. Gets the estimated yield of the investment.
459. @return the percentage
460. */
461. public double getInvestPercent()
462. {
463. return investPercent;
464. }
465.
466. /**
467. Sets the estimated yield of the investment.
468. @param x the percentage
469. */
470. public void setInvestPercent(double x)
471. {
472. investPercent = x;
473. }
474.
475. private double savings;
476. private double contrib;
477. private double income;
478. private int currentAge;
479. private int retireAge;
480. private int deathAge;
481. private double inflationPercent;
482. private double investPercent;
483.
484. private int age;
485. private double balance;
486. }
487.
488. /**
489. This panel draws a graph of the investment result.
490. */
491. class RetireCanvas extends JPanel
492. {
493. public RetireCanvas()
494. {
495. setSize(WIDTH, HEIGHT);
496. }
497.
498. /**
499. Sets the retirement information to be plotted.
500. @param newInfo the new retirement info.
501. */
502. public void setInfo(RetireInfo newInfo)
503. {
504. info = newInfo;
505. repaint();
506. }
507.
508. public void paintComponent(Graphics g)
509. {
510. Graphics2D g2 = (Graphics2D)g;
511. if (info == null) return;
512.
513. double minValue = 0;
514. double maxValue = 0;
515. int i;
516. for (i = info.getCurrentAge();
517. i <= info.getDeathAge(); i++)
518. {
519. double v = info.getBalance(i);
520. if (minValue > v) minValue = v;
521. if (maxValue < v) maxValue = v;
522. }
523. if (maxValue == minValue) return;
524.
525. int barWidth = getWidth() / (info.getDeathAge()
526. - info.getCurrentAge() + 1);
527. double scale = getHeight() / (maxValue - minValue);
528.
529. for (i = info.getCurrentAge();
530. i <= info.getDeathAge(); i++)
531. {
532. int x1 = (i - info.getCurrentAge()) * barWidth + 1;
533. int y1;
534. double v = info.getBalance(i);
535. int height;
536. int yOrigin = (int)(maxValue * scale);
537.
538. if (v >= 0)
539. {
540. y1 = (int)((maxValue - v) * scale);
541. height = yOrigin - y1;
542. }
543. else
544. {
545. y1 = yOrigin;
546. height = (int)(-v * scale);
547. }
548.
549. if (i < info.getRetireAge())
550. g2.setColor(colorPre);
551. else if (v >= 0)
552. g2.setColor(colorGain);
553. else
554. g2.setColor(colorLoss);
555. Rectangle2D bar = new Rectangle2D.Double(x1, y1,
556. barWidth - 2, height);
557. g2.fill(bar);
558. g2.setColor(Color.black);
559. g2.draw(bar);
560. }
561. }
562.
563. /**
564. Sets the color to be used before retirement.
565. @param color the desired color
566. */
567. public void setColorPre(Color color)
568. {
569. colorPre = color;
570. repaint();
571. }
572.
573. /**
574. Sets the color to be used after retirement while
575. the account balance is positive.
576. @param color the desired color
577. */
578. public void setColorGain(Color color)
579. {
580. colorGain = color;
581. repaint();
582. }
583.
584. /**
585. Sets the color to be used after retirement when
586. the account balance is negative.
587. @param color the desired color
588. */
589. public void setColorLoss(Color color)
590. {
591. colorLoss = color;
592. repaint();
593. }
594.
595. private RetireInfo info = null;
596.
597. private Color colorPre;
598. private Color colorGain;
599. private Color colorLoss;
600. private static final int WIDTH = 400;
601. private static final int HEIGHT = 200;
602. }
1. import java.util.*;
2. import java.awt.*;
3.
4. /**
5. These are the English non-string resources for the retirement
6. calculator.
7. */
8. public class RetireResources
9. extends java.util.ListResourceBundle
10. {
11. public Object[][] getContents() { return contents; }
12. static final Object[][] contents =
13. {
14. // BEGIN LOCALIZE
15. { "colorPre", Color.blue },
16. { "colorGain", Color.white },
17. { "colorLoss", Color.red }
18. // END LOCALIZE
19. };
20. }
1. import java.util.*;
2. import java.awt.*;
3.
4. /**
5. These are the German non-string resources for the retirement
6. calculator.
7. */
8. public class RetireResources_de
9. extends java.util.ListResourceBundle
10. {
11. public Object[][] getContents() { return contents; }
12. static final Object[][] contents =
13. {
14. // BEGIN LOCALIZE
15. { "colorPre", Color.yellow },
16. { "colorGain", Color.black },
17. { "colorLoss", Color.red }
18. // END LOCALIZE
19. };
20. }
1. import java.util.*;
2. import java.awt.*;
3.
4. /**
5. These are the Chinese non-string resources for the retirement
6. calculator.
7. */
8. public class RetireResources_zh
9. extends java.util.ListResourceBundle
10. {
11. public Object[][] getContents() { return contents; }
12. static final Object[][] contents =
13. {
14. // BEGIN LOCALIZE
15. { "colorPre", Color.red },
16. { "colorGain", Color.blue },
17. { "colorLoss", Color.yellow }
18. // END LOCALIZE
19. };
20. }
1. language=Language
2. computeButton=Compute
3. savings=Prior Savings
4. contrib=Annual Contribution
5. income=Retirement Income
6. currentAge=Current Age
7. retireAge=Retirement Age
8. deathAge=Life Expectancy
9. inflationPercent=Inflation
10. investPercent=Investment Return
11. retire=Age: {0,number} Balance: {1,number,currency}
1. language=Sprache 2. computeButton=Rechnen 3. savings=Vorherige Ersparnisse 4. contrib=Jhrliche Einzahlung 5. income=Einkommen nach Ruhestand 6. currentAge=Jetziges Alter 7. retireAge=Ruhestandsalter 8. deathAge=Lebenserwartung 9. inflationPercent=Inflation 10. investPercent=Investitionsgewinn 11. retire=Alter: {0,number} Guthaben: {1,number,currency}
1. language=\u8bed\u8a00
2. computeButton=\u8ba1\u7b97
3. savings=\u65e2\u5b58
4. contrib=\u6bcf\u5e74\u5b58\u91d1
5. income=\u9000\u4f11\u6536\u5165
6. currentAge=\u73b0\u5cad
7. retireAge=\u9000\u4f11\u5e74\u9f84
8. deathAge=\u9884\u671f\u5bff\u547d
9. inflationPercent=\u901a\u8d27\u81a8\u6da8
10. investPercent=\u6295\u8d44\u62a5\u916c
11. retire=\u5e74\u9f84: {0,number} \u603b\u7ed3: {1,number,currency}
![]()
Locale getLocale()
gets the current locale of the applet. The current locale is determined from the client computer that executes the applet.
[1] We have really everything in common with America nowadays, except, of course, language." Oscar Wilde.
| CONTENTS |